<?php

class adminController extends base
{
    public $compensateMile;  // 公里零数， 用于计算跑步 point_coordinate
    private $_function = ['post'=>'发帖','createActivity'=>'创建活动','publishComment'=>'评论及回复','chat'=>'私聊及群聊'];//黑名单禁用功能
    public function __construct()
    {
        parent::__construct('admin');
        // $this->checkPrivilege(common::request('a', 'R'));
        $compensateMile = 0;
        $this->load('admin');
        
        // 判断权限
        if(empty($this->realUser['uid']) || !$this->load('adminList')->isAdminByHupuUid($this->realUser['uid']))
        {
            echo 'jrs, 不要四处乱看哦～～';
            exit();
        }
    }
    public function checkPrivilege($action)
    {
        $adminId = $this->realUser['uid'];
        $restrictUser = array(
            '18640971' => array('init','gearList','gearInfo','gearAction','brandInfo','brandList','brandAction','gearHotKw','setGearHotKw','gearHomeBest','setGearHmBest','gearSetList','gearSetInfo','gearSetAction','gearRecList'),
        );
        if(isset($restrictUser[$adminId]) && !in_array($action, $restrictUser[$adminId]))
        {
            $this->view->display('index');
            exit;
        }
    }
    // 初始页面
    public function doinit()
    {
        $this->view->display('index');
    }
    //删除用户
    public function doclearUser()
    {
        $username = trim(common::request('username', 'P'));
        $client_id = trim(common::request('client', 'P'));
        $tips = '';

        //删除client_id
        if (!empty($client_id))
        {
            $c = $this->db->getRowTable('r_client', array(), "client='{$client_id}'");
            $this->db->delDataTable('r_client', "client='{$client_id}'");
            $r = $this->redis->hdel(REDIS_PREFIX . 'ClientId', $client_id);

            if ($r)
            {
                $tips .= 'ClientId--' . $client_id . '删除成功<br>';
            }
        }
        if (!empty($username))
        {
            $user = $this->db->getRowTable('r_user', array(), "nickname='{$username}'");

            if (empty($user))
            {
                $tips .= '查无此用户--' . $username;
            }
            $key = REDIS_PREFIX . 'UserInfo_' . $user['uid'];
            $this->redis->del($key);
            $this->db->delDataTable('r_user', "nickname='{$username}'");
            $this->db->delDataTable('r_data', "uid='{$user['uid']}'");

            if ($user['lastcid'])
            {
                $c = $this->db->getRowTable('r_client', array(), "cid='{$user['cid']}'");
                $this->db->delDataTable('r_client', "cid='{$user['cid']}'");
                $r = $this->redis->hget(REDIS_PREFIX . 'ClientId', $c['client']);

                if ($r)
                {
                    $tips .= 'ClientId--删除成功<br>';
                }
            }

            //删除排名
            $rank = $this->redis->zrevrank(REDIS_PREFIX . 'StandingsMileage', $user['uid']);
            if ($rank !== FALSE)
            {
                $this->redis->zrem(REDIS_PREFIX . 'StandingsMileage', $user['uid']);
            }

            $tips .= $username . '删除成功';
        } else
        {
            $tips = '';
        }

        $this->view->assign('tips', $tips);
        $this->view->display("clearUser");
    }
    /**
     * 用户列表
     */
    public function douserList()
    {
        $s = common::request('s','R');
        $query = ' where 1';
        $search = array('nickname' => '', 
                        'gender'    => '',
                        'device'    => '',
                        'total_rate'    => '',
                        'qq'    => -1,
                        'sina'    => -1,
                        'weixin'    => -1,
                        'renren'    => -1,
                        'sort'    => 'uid',
                        'order'    => 'DESC',
                        'phone' =>'',
                        'address_book' => '',
                        'tagId' => '',
                        );
        $parameter = '';//分页跳转的参数
        if ($s == "search")
        {
            $nickname = common::request('nickname', 'R', '');
            $gender = common::request('gender','R','');
            $device = common::request('device','R','');
            $total_rate = common::request('total_rate','R','');
            $qq = common::request('qq','R',0);
            $sina = common::request('sina','R',0);
            $weixin = common::request('weixin','R',0);
            $renren = common::request('renren','R',0);

            $sort = common::request('sort','P','uid');
            $order = common::request('order','P','DESC');
            $phone = common::request('phone','R','');
            
            $address_book = common::request('address_book','R','');
            $tagId = common::request('tagId','R','');

            $search = compact('nickname', 'gender','device', 'total_rate', 'qq', 'sina','weixin', 'renren', 'sort', 'order','phone','address_book','tagId');
            $parameter = compact('s','nickname', 'gender','device', 'total_rate', 'qq', 'sina','weixin', 'renren','sort','order','phone','address_book','tagId');
            $parameter = '&'.urldecode(http_build_query($parameter, NULL, '&'));

            //$query .= empty($nickname) ? "":" and  (u.uid='$nickname' or u.nickname like \"%$nickname%\") ";
            $query .= empty($gender) ? "" : " and u.gender=$gender ";
            $query .= empty($device) ? "" : " and c.client_type=$device ";
            $query .= empty($total_rate)  ? ""  : " and u.total_rate >= $total_rate ";
            $query .= empty($phone) ? "" :" and (u.phone='$phone' or u.phone like \"%$phone%\") ";
            
            $qq >= 0 && $query .= ($qq == 0) ? ' and u.qq=0' :' and u.qq > 0';
            $sina >= 0 && $query .= ($sina == 0) ? ' and u.sina=0' :' and u.sina > 0';
            $weixin >= 0 && $query .= ($weixin == 0) ? ' and u.weixin=0' :' and u.weixin > 0';
            $renren >= 0 && $query .= ($renren== 0) ? ' and u.renren=0' :' and u.renren > 0';
            
            if($address_book!=''){
                //$query .= ($address_book == 1)? ' GROUP BY c.client HAVING address_count = 0' :' GROUP BY c.client HAVING address_count > 0';
                $query .= ($address_book == 1) ? ' AND NOT':' AND';
                $query .=' EXISTS (SELECT id FROM r_address_book AS a WHERE a.clientid = c.client)';
            }
            
            if($tagId){
                $query = "left join r_usertag on r_usertag.uid = u.uid WHERE r_usertag.tagId = $tagId";
            }
        }
        
        //分页
        require FILE . 'lib/page.class.php';
        $listNum = 10;
        $p = common::request('p', 'G', 1);
        $start = ($p - 1) * $listNum;
        
        if(isset($nickname) && $nickname != ''){
            $searcher = $this->load('xunSearch')->init('user');
            $num = $searcher->getCount("uid:$nickname OR $nickname");
            
            $res = $searcher->result("uid:$nickname OR $nickname",null,$listNum,$start);
            $uid_in = [];
            foreach($res as $v){
                $uid_in[] = $v->uid;
            }
            $uid_in = "('".implode("','",$uid_in)."')";
            $query = ' WHERE u.uid IN '.$uid_in;
            $start = 0;
        }else{
            $num = $this->db->getOne("select count(u.uid),
                                    (select count(*) from r_address_book as a where c.client=a.clientid) as address_count
                                    from r_user u 
                                    left join r_client c on u.cid=c.cid ".$query);
        }
        $page = new Page($num, $listNum, $parameter);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);
        
        $sort= $search['sort'];
        $order= $search['order'];
        $phone= $search['phone'];
        $sql = "select u.*,c.client_type, 
                case when u.sina !=0 then (select openid from r_social_user where sid=u.sina) end as weiboID, 
                (select count(*) from r_address_book as a where c.client=a.clientid group by c.client) as address_count
                FROM r_user as u
                left join r_client as c on u.cid=c.cid ".$query."
                order by {$sort} {$order} limit $start,$listNum";

        $userData = $this->db->getAll($sql);
        $uids = [];
        foreach ($userData as $key => $v) {
            $userData[$key]['phone'] = substr_replace($v['phone'],'****',3,4);
            $uids[] = $v['uid'];
        }
        
        $tagList = json_decode($this->redis->get(REDIS_PREFIX.'UserTagList'),true);
        $userTag = [];
        if($uids){
            $sql = "SELECT uid,tagId from r_usertag where uid IN('".implode("','",$uids)."')";
            $rows = $this->db->getAll($sql);
            foreach($rows as $row){
                if(!isset($userTag[$row['uid']])){
                    $userTag[$row['uid']] = '';
                }
                $userTag[$row['uid']] .= $tagList[$row['tagId']].',';
            }
        }
        
        $this->view->assign('userTag',$userTag);
        $this->view->assign('tagList',$tagList);
        $this->view->assign('userData', $userData);
        $this->view->assign('search', $search);
        $this->view->display('userList');
    }
    /*
        游客用户
    */
    public function dovisitorList()
    {
        $s = common::request('s','R');
        $query = ' where 1';
        $search = array('nickname' => '',
            'gender'    => '',
            'device'    => '',
            'total_rate'    => '',
            'sort'    => 'vid',
            'order'    => 'DESC'
        );
        $parameter = '';//分页跳转的参数
        if ($s == "search")
        {
            $nickname = common::request('nickname', 'R', '');
            $gender = common::request('gender','R','');
            $device = common::request('device','R','');
            $total_rate = common::request('total_rate','R','');

            $sort = common::request('sort','P','vid');
            $order = common::request('order','P','DESC');

            $search = compact('nickname', 'gender','device', 'total_rate', 'sort', 'order');

            $parameter = compact('s','nickname', 'gender','device', 'total_rate');
            $parameter = '&'.urldecode(http_build_query($parameter, NULL, '&'));

            $query .= empty($nickname) ? "":" and  (v.vid='$nickname' or v.nickname='$nickname') ";
            $query .= empty($gender) ? "" : " and v.gender=$gender ";
            $query .= empty($device) ? "" : " and c.client_type=$device ";
            $query .= empty($total_rate)  ? ""  : " and v.total_rate >= $total_rate ";
        }
        $sort= $search['sort'];
        $order= $search['order'];
        $p = common::request('p', 'G', 1);
        $num = $this->db->getOne("select count(vid) from r_visitor as v left join r_client as c on v.vid=c.cid ". $query);
        //分页
        require FILE . 'lib/page.class.php';
        $listNum = 10;
        $page = new Page($num, $listNum, $parameter);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);

        $start = ($p - 1) * $listNum;
        $sql = "select v.*,c.client_type from r_visitor as v left join r_client as c on v.cid=c.cid ".$query." order by {$sort} {$order} limit $start,$listNum";
        $userData = $this->db->getAll($sql);

        $this->view->assign('userData', $userData);
        $this->view->assign('search', $search);
        $this->view->display('visitorList');
    }
    /**
     * 用户批操作
     */
    public function dobatchUser()
    {
        $uids = common::request('uid','P');
        $action = common::request('action','P');
        if(empty($uids))
        {
            exit('你不要逗我好吗？');
        }
        $talentKey = REDIS_PREFIX .'talentUsers';
        if($action == 'setTalentUser')
        {
            foreach ($uids as $key => $uid) {
                $this->redis->zadd($talentKey, time(), $uid);
            }
        }
        elseif($action == 'cancelTalentUser')
        {
            foreach ($uids as $key => $uid) {
                $this->redis->zrem($talentKey, $uid);
            }
        }
        else
        {
            exit('你这么干是犯法的你知道吗？');
        }
        echo "操作完成，&nbsp;&nbsp;&nbsp;<a href='index.php?c=admin&a=talentUserList'>查看达人列表</a>";
        echo "<br>";
        echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='".$_SERVER['HTTP_REFERER']."'>回到上一页</a>";
        exit;
    }
    
    /*
     * 勋章列表
     */
    public function domedalList(){
        $p = common::request('p','G',1);
        
        $num = $this->db->getOne("select count(*) from r_medal");
        $listNum = 50;
        $start = ($p -1) * $listNum;
        require FILE . 'lib/page.class.php';
        $page = new Page($num, $listNum);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);
        
        $medals = $this->db->getAll("select * from r_medal order by medal_id desc limit $start,$listNum");
        /*$medals = $this->db->getAll("SELECT m.*, sum(r.number) number FROM r_medal m LEFT JOIN r_medal_record r ON m.medal_id = r.medal_id GROUP BY m.medal_id order by m.medal_id desc  limit $start,$listNum");*/
        
        $this->view->assign('medalCate',common::$medalCate);
        $this->view->assign('medalList',$medals);
        $this->view->display('medalList');
    }
    
    /*
     * 勋章详情
     */
    public function domedalInfo(){
        $medal_id = common::request('medal_id','G');
        
        if(!empty($medal_id)){
            $medalInfo = $this->load('medal')->getMedalInfo($medal_id);
        }else{
            $medalInfo = [
                'medal_id' => '',
                'medal_name' => '',
                'word' => '',
                'limit' => 1,
                'img1' => '',
                'img2' => '',
                'cate' => '1',
                'mileage_limit' => 0,
                'gender' => 0,
                'start_time' => '',
                'end_time' => '',
                'isCustom' => 1,
                'tag' => '0'
            ];
        }
        
        $this->view->assign('medalCate',common::$medalCate);
        $this->view->assign('medalInfo',$medalInfo);
        $this->view->display('medalInfo');
    }
    
    /*
     * 勋章编辑
     */
    public function domedalAction(){
        $medal_id = common::request('medal_id','P');
        $data = [
            'medal_id' => $medal_id,
            'medal_name' => common::request('medal_name','P'),
            'word' => common::request('word','P',''),
            'limit' => common::request('limit','P'),
            'img1' => common::request('img1','P'),
            'img2' => common::request('img2','P'),
            'cate' => common::request('cate','P'),
            'mileage_limit' => common::request('mileage_limit','P'),
            'gender' => common::request('gender','P'),
            'isCustom' => common::request('isCustom','P'),
            'start_time' => strtotime(common::request('start_time','P')),
            'end_time' => strtotime(common::request('end_time','P')),
        ];
        //图片
        $qiniu_mod = $this->load('qiniu');
        $imgName = md5(common::getHashStr(6).time());
        $img1 = $qiniu_mod->uploadQiNiuImg('newImg1',$imgName);
        $imgName = md5(common::getHashStr(6).time());
        $img2 = $qiniu_mod->uploadQiNiuImg('newImg2',$imgName);
        $img1 && $data['img1'] = $img1;
        $img2 && $data['img2'] = $img2;
        $data['word'] = str_replace(["\n","\r"],['\n',''],$data['word']);
        //时间
        if($data['isCustom'] == 1){
            $data['start_time'] = $data['start_time'] ? strtotime(date('2016-m-d H:i:s',$data['start_time'])) : 0;
            $data['end_time'] = $data['start_time'] ? strtotime(date('2016-m-d H:i:s',$data['end_time'])) : 0;
        }
        $medal_mod = $this->load('medal');
        
        if($medal_id){
            $res = $medal_mod->update($data);
        }else{
            $res = $medal_mod->insert($data);
        }
        if($res){
            echo '<a href="index.php?c=admin&a=medalList">操作成功 ------- 查看</a>';
            exit;
        }else{
            echo '<a href="index.php?c=admin&a=medalList">失败 ------- 查看</a>';
            exit;
        }
    }
    
    /**
     * 勋章获得列表
    */
    public function domedalRecordList()
    {
        $uid = common::request('uid', 'G', 0);
        $p = common::request('p', 'G', 1);
        $listNum = 20;
        $start = ($p-1) * $listNum;

        //分页
        if(empty($uid))
        {
            $num =1000;
        }
        else
        {
            $num_sql = "select count(*) from r_medal_record where uid = '{$uid}'";
            $num = $this->db->getOne($num_sql);
        }

        require FILE . 'lib/page.class.php';
        $page = new Page($num, $listNum);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);


        $sql = 'select * from r_medal_record ';
        !empty($uid) && $sql .= "where uid = '{$uid}'";
        $sql .= " order by add_time DESC limit $start, $listNum";

        $medalList = $this->db->getAll($sql);
        if($medalList)
        {
            foreach ($medalList as $key=> & $value) {
                $medalInfo = $this->load('medal')->getMedalInfo($value['medal_id']);
                if($medalInfo)
                {
                    $userInfo = $this->load('client')->getUserInfo($value['uid']);
                    $value['nickname'] = isset($userInfo['nickname']) ? $userInfo['nickname'] : '查无此人';
                    $value['header'] = isset($userInfo['header']) ? $userInfo['header'] : 'static/u/defaultHeader.png';
                    $value['medal_name'] = $medalInfo['medal_name'];
                    $value['medal_img'] = $medalInfo['img1'];
                }
                else
                {
                    unset($medalList[$key]);
                }
            }
        }

        $this->view->assign('medalList', $medalList);
        $this->view->display('medalRecordList');
    }
    /**
     * 达人列表
     */
    public function dotalentUserList()
    {
        $p = common::request('p', 'G', 1);
        $num = $this->redis->zcard(REDIS_PREFIX .'talentUsers');
        //分页
        require FILE . 'lib/page.class.php';
        $listNum = 20;
        $page = new Page($num, $listNum);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);

        $start = ($p - 1) * $listNum;
        $limit = array($start, $listNum);
        $uids = $this->redis->ZREVRANGEBYSCORE(REDIS_PREFIX .'talentUsers', '+inf', '-inf', array('limit' => $limit));
        $talentUsers = array();
        if($uids)
        {
            foreach ($uids as $key => $uid) {
                $userInfo = $this->db->getRowTable('r_user', array(), "uid = {$uid}");
                if($userInfo)
                {
                    $userInfo['client_type'] = $this->db->getOne("select client_type from r_client where cid = {$userInfo['cid']}");
                    $userInfo['weiboID'] = $this->db->getOne("select openid from r_social_user where sid = {$userInfo['sina']}");
                    $talentUsers[] = $userInfo;
                }
            }
        }

        $this->view->assign('userData', $talentUsers);
        $this->view->assign('search', 0);
        $this->view->display('userList');
    }
    public function douserinfo()
    {
        $uid = common::request('uid', 'G');
        $userInfo = $this->db->getRowTable('r_user', array(), "uid={$uid}");

        if(common::request('type') == 'json')
        {
            exit(json_encode($userInfo ? $userInfo : []));
        }

        $sql = "select * from r_medal_record where uid = '{$uid}' order by record_id DESC";
        $medalList = $this->db->getAll($sql);
        if($medalList)
        {
            foreach ($medalList as $key=> & $value) {
                $medalInfo = $this->load('medal')->getMedalInfo($value['medal_id']);
                if($medalInfo)
                {
                    $userInfo = $this->load('client')->getUserInfo($value['uid']);
                    $value['nickname'] = isset($userInfo['nickname']) ? $userInfo['nickname'] : '查无此人';
                    $value['header'] = isset($userInfo['header']) ? $userInfo['header'] : 'static/u/defaultHeader.png';
                    $value['medal_name'] = $medalInfo['medal_name'];
                    $value['medal_img'] = $medalInfo['img1'];
                }
                else
                {
                    unset($medalList[$key]);
                }
            }
        }

        $this->view->assign('medalList',$medalList);
        $this->view->assign('user', $userInfo);
        $this->view->display('userinfo');
    }

    /**
     * 删除用户信息和跑步记录
     */
    public function dodelUser()
    {
        $uid = common::request('uid', 'G');
        $tips = '';

        if (!empty($uid))
        {
            $user = $this->db->getRowTable('r_user', array(), "uid='{$uid}'");

            if (empty($user))
            {
                $tips .= '查无此用户--';
            }
            $key = REDIS_PREFIX . 'UserInfo_' . $user['uid'];
            $this->redis->del($key);
            $this->db->delDataTable('r_user', "uid='{$uid}'");
            $this->db->delDataTable('r_data', "uid='{$user['uid']}'");
            $this->db->delDataTable('r_news_collection', "uid='{$user['uid']}'");
            $this->db->delDataTable('r_news_comment', "uid='{$user['uid']}'");
            $this->db->delDataTable('r_runLevelRecord', "uid='{$user['uid']}'");
            $this->db->delDataTable('r_UCLightsRecord', "uid='{$user['uid']}'");

            /*
            if ($user['lastcid'])
            {
                $c = $this->db->getRowTable('r_client', array(), "cid='{$user['cid']}'");
                $this->db->delDataTable('r_client', "cid='{$user['cid']}'");
                $r = $this->redis->hget(REDIS_PREFIX . 'ClientId', $c['client']);

                if ($r)
                {
                    $tips .= 'ClientId--删除成功<br>';
                }
            }
            */
            if ($user['sid'])
            {
                $this->db->delDataTable('r_sina_user', "uid='{$user['uid']}'");
                $key = REDIS_PREFIX . 'SinaFriends_' . $user['uid'];

                $this->redis->del($key);
            }

            //删除排名
            $rank = $this->redis->zrevrank(REDIS_PREFIX . 'StandingsMileage', $user['uid']);
            if ($rank !== FALSE)
            {
                $this->redis->zrem(REDIS_PREFIX . 'StandingsMileage', $user['uid']);
            }

            $tips .= $user['nickname'] . '删除成功, uid为' . $user['uid'];
        } else
        {
            $tips = '';
        }

        $this->view->assign('tips', $tips);
        $this->view->display("clearUser");
    }

    /**
     * 个人跑步历史记录
     */
    public function doshowHistory()
    {
        $uid = common::request('uid','G');
        $p = common::request('p', 'G', 1);
        $t = common::request('t','G',1);
        $overSpeed = common::request('overSpeed', 'G', 0);
        $overSpeed = intval($overSpeed);
        $overSpeed > 1 && $overSpeed = 1;

         $abnorData=common::$abnorData;
        $this->view->assign('abnorData', $abnorData);

        $where_clause = $overSpeed > 0 ? " where overSpeed = '{$overSpeed}'": '';

        $r_table = $t == 1 ?'r_data' : 'r_visitor_data';
        $sql_where = $t == 1 ?"uid = {$uid}" : "vid = {$uid}";
        $overSpeed > 0 && $sql_where .=  " and overSpeed = '1'";

        $num = $this->db->getOne("select count(did) from {$r_table} where ".$sql_where);
        //分页
        require FILE . 'lib/page.class.php';
        $listNum = 10;
        $page = new Page($num, $listNum);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);

        $start = ($p - 1) * $listNum;
        if($t == 1)
            $runData = $this->db->getAll("select d.*,de.coordinate from {$r_table} as d left join r_data_ext de on d.did=de.did where ".$sql_where." order by d.did desc limit $start, $listNum");
        else
            $runData = $this->db->getAll("select * from {$r_table} where ".$sql_where." order by did desc limit $start, $listNum");
        $runner = $t == 1 ? $this->load('client')->getUserInfo($uid) : $this->load('client')->getVisitorInfo($uid);
        if($runData)
        {
            foreach ($runData as $key => &$v) {
                $uncompress = @gzuncompress($v['coordinate']);
                $v['coordinate'] = $uncompress === false ? $v['coordinate'] : $uncompress;
                $v['nickname'] = $runner['nickname'];
            }
        }
        $this->view->assign('runData', $runData);
        $this->view->assign('type', $t);
        $this->view->assign('overSpeedUrl', stripos($_SERVER['REQUEST_URI'], '&overSpeed=1') ? $_SERVER['REQUEST_URI'] : $_SERVER['REQUEST_URI'].'&overSpeed=1');
        $this->view->display('showHistory');
    }
    /**
     * 添加个人跑步数据
     */
    public function doaddUserRunDataBak()
    {
        $type = common::request('type', 'G', 'add');
        $message = '';
        $targetType = array('mileage' => '里程','elapsedtime' =>'跑步时间','calorie' =>'卡路里');
        $expression_corn = array('1'=>'feeling_1_nor.png','2'=>'feeling_2_nor.png','3'=>'feeling_3_nor.png','4'=>'feeling_4_nor.png','5'=>'feeling_5_nor.png','6'=>'feeling_6_nor.png','7'=>'feeling_7_nor.png');
        if($type != 'insert')
        {
            $runData = array(
                            'uid' => '',
                            'mileage' => 0,
                            'elapsedtime' => 0,
                            'calorie' => 0,
                            'city' => '',
                            'updatetime' => time(),
                            'record_img' => array('','','','',''),
                            'target_type' => '',
                            'target_rate' => 0,
                            'run_mood' => '',
                            'expression_id' => 1,
                            'detail_speed' => ''
                    );
            $this->view->assign('message', $message);
            $this->view->assign('runData', $runData);
            $this->view->assign('targetType', $targetType);
            $this->view->assign('expression_corn', $expression_corn);
            $this->view->display('addRunData');
        }
        else
        {
            $uid = common::request('uid', 'P');
            $userInfo = $this->redis->hgetall(REDIS_PREFIX . 'UserInfo_' . $uid);
            if(empty($userInfo))
            {
                exit('用户不存在！');
            }
            $mileage = common::request('mileage', 'P');
            $elapsedtime = common::request('elapsedtime', 'P');
            $calorie = common::request('calorie', 'P');
            $city = common::request('runcity', 'P');
            $updatetime = common::request('updatetime', 'P');
            $clickPoint = common::request('clickPoint', 'P');
            $target_type = common::request('target_type', 'P');
            $target_rate = common::request('target_rate', 'P',0);
            $run_mood = common::request('run_mood', 'P');
            $expression_id = common::request('expression_id', 'P');
            $detail_speed = common::request('detail_speed', 'P');
            $order_id = time();
            $updatetime = strtotime($updatetime);
            if(empty($mileage)|| empty($elapsedtime)|| empty($calorie)|| empty($city)|| empty($clickPoint)|| empty($detail_speed))
            {
                exit('参数不完整');
            }
            $detail_speed = '["'.str_replace('|', '","', $detail_speed).'"]';
            $coor = $this->createAllCoordinate($clickPoint);
            $coordinate = '['.implode(',', $coor['coordinate']).']';
            $point_coordinate = '['.implode(',', $coor['point_coordinate']).']';
            $southWestPoint = $coor['southWestPoint'];
            $northEastPoint = $coor['northEastPoint'];

            $record_img = array();
            // require FILE . 'lib/image.class.php';
            // for($i = 0; $i <= 4; $i++)
            // {
            //     $i = $i==0 ? '' : $i;
            //     if (!empty($_FILES['record_img'.$i])) //跑步记录图片
            //     {
            //         $loadImg = $this->load('run')->uploadRecordImg('record_img'.$i);
            //         $loadImg && $record_img[] = common::realUrl($loadImg);
            //     }
            // }
            $recordImgCount = count($record_img);
            $record_img = json_encode($record_img);

            $elapsedtime < 1 && $elapsedtime = 1;
            $mileage < 0.01 && $mileage = 0.01;
            $speed = round($mileage / ($elapsedtime / 3600), 1);
            $speed < 0.1 && $speed = 0.1;
            $legspeed = round(($elapsedtime / 60) / $mileage, 1);
            $legspeed < 0.1 && $legspeed = 0.1;
            $calorie = round($calorie , 1);
            $calorie < 0.1 && $calorie = 0.1;
            $target_rate > 1 && $target_rate = 1.00;
            $medal = $this->getRunMedal($uid, compact('mileage', 'elapsedtime','updatetime','target_rate'));
            $five_time = $this->getBestSumValue(json_decode($detail_speed, true), 5) * 60;
            $ten_time = $this->getBestSumValue($detail_speed, 10) * 60;
            $half_mtime = $this->getBestSumValue($detail_speed, 21) * 60;
            $mara_time = $this->getBestSumValue($detail_speed, 42) * 60;
            if($five_time >0 && $five_time < $userInfo['max_five_time'])    $medal[] = 126;
            if($ten_time >0 && $five_time < $userInfo['max_ten_time'])      $medal[] = 127;
            if($half_mtime >0 && $five_time < $userInfo['max_half_mtime'])  $medal[] = 128;
            if($mara_time >0 && $five_time < $userInfo['max_mara_time'])    $medal[] = 129;
            // 验证并添加勋章记录
            $medal = $this->load('medal')->verifyRunMedal($uid, json_encode($medal), $updatetime);
            $runData = array(
                            'uid' => $uid,
                            'mileage' => $mileage,
                            'elapsedtime' => $elapsedtime,
                            'speed' => $speed,
                            'legspeed' => $legspeed,
                            'calorie' => $calorie,
                            'city' => $city,
                            'updatetime' => $updatetime,
                            'addtime' => time(),
                            'record_img' => $record_img,
                            'order_id' => $order_id,
                            'point_coordinate' => $point_coordinate,
                            'target_type' => $target_type,
                            'target_rate' => $target_rate,
                            'run_mood' => $run_mood,
                            'expression_id' => $expression_id,
                            'detail_speed' => $detail_speed,
                            'recordImgCount' => $recordImgCount,
                            'southWestPoint' => $southWestPoint,
                            'northEastPoint' => $northEastPoint,
                            'medal' => $medal,
                            'five_time' => $five_time,
                            'ten_time' => $ten_time,
                            'half_mtime' => $half_mtime,
                            'mara_time' => $mara_time,
                    );
            $did = $this->db->insertRowTable('r_data', $runData);
            if($did)
            {
                //将跑步坐标插入到扩展表中
                $extData = array('did'=>$did,'coordinate' => gzcompress($coordinate, 9));
                $this->db->insertRowTable('r_data_ext',$extData);
                $this->redis->hset(REDIS_PREFIX . 'runDataOrder_' . $uid, $order_id, 1);

                $modify = array(
                                'uid' => $uid,
                                'modify_type' => 0,
                                'add_time' => $order_id,
                                'modify_time' => $order_id
                    );
                $this->load('run')->runDataModify($did, $modify);

                $upData = array(
                    'total_mileage' => round($userInfo['total_mileage'] + $mileage, 2),
                    'total_elapsedtime' => $userInfo['total_elapsedtime'] + $elapsedtime,
                    'total_calorie' => round($userInfo['total_calorie'] + $calorie, 1),
                    'total_rate' => $userInfo['total_rate'] + 1,
                    'level' => common::getLevel(round($userInfo['total_mileage'] + $mileage, 2))
                );

                $mileage > $userInfo['max_mileage'] && $upData['max_mileage'] = $mileage;
                $elapsedtime > $userInfo['max_elapsedtime'] && $upData['max_elapsedtime'] = $elapsedtime;
                $five_time >0 && $five_time < $userInfo['max_five_time'] && $upData['max_five_time'] = $five_time;
                $ten_time >0 && $ten_time < $userInfo['max_ten_time'] && $upData['max_ten_time'] = $ten_time;
                $half_mtime >0 && $half_mtime < $userInfo['max_half_mtime'] && $upData['max_half_mtime'] = $half_mtime;
                $mara_time >0 && $mara_time < $userInfo['max_mara_time'] && $upData['max_mara_time'] = $mara_time;
                $this->load('client')->setUserInfo($uid, $upData);
                // 更新日跑步数据
                $this->load('run')->addDayRunData($uid, compact('mileage','elapsedtime','calorie', 'updatetime'));
                $userInfo['level'] < $upData['level'] && $this->load('run')->runLevelUpRecord($uid, $upData['level'], $upData['total_mileage'],'', $updatetime);
                if($target_rate >= 1)
                {
                    $this->load('client')->userEnergyChange($uid, 'target', $mileage);
                }
                elseif($mileage > 1)
                {
                    $this->load('client')->userEnergyChange($uid, 'run', $mileage);
                }
                // 更新用户好友排行榜
                $this->load('run')->updateUserFStandings($uid, $mileage, $updatetime);
                // 更新用户最近跑步记录
                $runRecord = compact('mileage','elapsedtime','city','calorie','updatetime');
                $this->load('client')->getLatestRunRecord($uid, $runRecord);
                // 更新用户跑步等级信息
                $this->load('client')->getUserLevelInfo($uid, TRUE);
                // 更新用户里程排名
                $this->load('run')->setClientMileageStandingsRank($uid, $upData['total_mileage']);

                // 更新群组跑步数据
                $groupData = compact('did','mileage','elapsedtime','city','calorie','updatetime','five_time','ten_time','half_mtime','mara_time');

                $rel = $this->load('group')->addGroupRunData($uid,$groupData);

                header("Location:index.php?c=admin&a=showHistory&uid=".$uid."&t=1\n");
                exit;
            }
            exit('添加个人跑步数据失败');
        }
    }

    /**
     * 添加个人跑步数据
     */
    public function doaddUserRunData()
    {
        $type = common::request('type', 'G', 'add');
        $message = '';
        $targetType = array('mileage' => '里程','elapsedtime' =>'跑步时间','calorie' =>'卡路里');
        $expression_corn = array('1'=>'feeling_1_nor.png','2'=>'feeling_2_nor.png','3'=>'feeling_3_nor.png','4'=>'feeling_4_nor.png','5'=>'feeling_5_nor.png','6'=>'feeling_6_nor.png','7'=>'feeling_7_nor.png');
        if($type != 'insert')
        {
            $runData = array(
                'uid' => '',
                'mileage' => 0,
                'elapsedtime' => 0,
                'calorie' => 0,
                'city' => '',
                'updatetime' => time(),
                'record_img' => array('','','','',''),
                'target_type' => '',
                'target_rate' => 0,
                'run_mood' => '',
                'expression_id' => 1,
                'detail_speed' => ''
            );
            $this->view->assign('message', $message);
            $this->view->assign('runData', $runData);
            $this->view->assign('targetType', $targetType);
            $this->view->assign('expression_corn', $expression_corn);
            $this->view->display('addRunData');
        }
        else
        {
            $uid = common::request('uid', 'P');
            $userInfo = $this->redis->hgetall(REDIS_PREFIX . 'UserInfo_' . $uid);
            if(empty($userInfo))
            {
                exit('用户不存在！');
            }
            $mileage = common::request('mileage', 'P');
            $elapsedtime = common::request('elapsedtime', 'P');
            $calorie = common::request('calorie', 'P');
            $city = common::request('runcity', 'P');
            $updatetime = common::request('updatetime', 'P');
            $clickPoint = common::request('clickPoint', 'P');
            $target_type = common::request('target_type', 'P');
            $target_rate = common::request('target_rate', 'P',0);
            $run_mood = common::request('run_mood', 'P');
            $expression_id = common::request('expression_id', 'P');
            $detail_speed = common::request('detail_speed', 'P');
            //$order_id = time();
            $order_id = floor(microtime(true)*1000);//精确到微秒
            $updatetime = strtotime($updatetime);
            if(empty($mileage)|| empty($elapsedtime)|| empty($calorie)|| empty($city)|| empty($clickPoint)|| empty($detail_speed))
            {
                exit('参数不完整');
            }
            $detail_speed = '["'.str_replace('|', '","', $detail_speed).'"]';
            $coor = $this->createAllCoordinate($clickPoint);
            //$coordinate = '['.implode(',', $coor['coordinate']).']';
            $coordinate = json_encode($coor['coordinate']);
            $point_coordinate = '['.implode(',', $coor['point_coordinate']).']';
            $southWestPoint = $coor['southWestPoint'];
            $northEastPoint = $coor['northEastPoint'];

            $record_img = array();
            // require FILE . 'lib/image.class.php';
            // for($i = 0; $i <= 4; $i++)
            // {
            //     $i = $i==0 ? '' : $i;
            //     if (!empty($_FILES['record_img'.$i])) //跑步记录图片
            //     {
            //         $loadImg = $this->load('run')->uploadRecordImg('record_img'.$i);
            //         $loadImg && $record_img[] = common::realUrl($loadImg);
            //     }
            // }
            $recordImgCount = count($record_img);
            $record_img = json_encode($record_img);

            $elapsedtime < 1 && $elapsedtime = 1;
            $mileage < 0.01 && $mileage = 0.01;
            $speed = round($mileage / ($elapsedtime / 3600), 1);
            $speed < 0.1 && $speed = 0.1;
            $legspeed = round(($elapsedtime / 60) / $mileage, 1);
            $legspeed < 0.1 && $legspeed = 0.1;
            $calorie = round($calorie , 1);
            $calorie < 0.1 && $calorie = 0.1;
            $target_rate > 1 && $target_rate = 1.00;
            $medal = $this->getRunMedal($uid, compact('mileage', 'elapsedtime','updatetime','target_rate'));
            $five_time = $this->getBestSumValue($detail_speed, 5) * 60;
            $ten_time = $this->getBestSumValue($detail_speed, 10) * 60;
            $half_mtime = $this->getBestSumValue($detail_speed, 21) * 60;
            $mara_time = $this->getBestSumValue($detail_speed, 42) * 60;
            if($five_time >0 && $five_time < $userInfo['max_five_time'])    $medal[] = 126;
            if($ten_time >0 && $five_time < $userInfo['max_ten_time'])      $medal[] = 127;
            if($half_mtime >0 && $five_time < $userInfo['max_half_mtime'])  $medal[] = 128;
            if($mara_time >0 && $five_time < $userInfo['max_mara_time'])    $medal[] = 129;
            $runData = array(
                'uid' => $uid,
                'mileage' => $mileage,
                'elapsedtime' => $elapsedtime,
                'calorie' => $calorie,
                'city' => $city,
                'coordinate'=>$coordinate,
                'point_coordinate' => $point_coordinate,
                'record_img' => $record_img,
                'updatetime' => $updatetime,
                'order_id' => $order_id,
                'target_type' => $target_type,
                'target_rate' => $target_rate,
                'run_mood' => $run_mood,
                'expression_id' => $expression_id,
                'detail_speed' => $detail_speed,
                'recordImgCount' => $recordImgCount,
                'southWestPoint' => $southWestPoint,
                'northEastPoint' => $northEastPoint,
                'medal' => json_encode($medal),
                'five_time' => $five_time,
                'ten_time' => $ten_time,
                'half_mtime' => $half_mtime,
                'mara_time' => $mara_time
            );

            $time = time();
            $tokenStr = md5($userInfo['uid'].$time.$this->config['tokenStr']);
            $tokenArr = array($uid, $time, $tokenStr);
            $token = implode('-', $tokenArr);
            $sign  = $this->config['app_key'];
            $domin = $this->config['host'];
            $runData['token'] = $token;
            $data = common::getContents("$domin?c=run&a=adminUploadRunData&sign=$sign&v=2.0.0", $runData, 10, 'POST', null,'u='.$_COOKIE ['u']);
            var_dump($data);//预留  一旦出错，错误能打印在后台
            $data = json_decode($data, true);
            if (!$data)  {
                exit('上传失败');
            } else{
                if(isset($data['error'])) {
                    exit($data['error']['text']);
                }else {
                    header("Location:index.php?c=admin&a=showHistory&uid=".$uid."&t=1\n");
                    exit;
                }
            }
        }
    }
     /**
     * 生成跑步坐标 相关数据
     */
    private function createAllCoordinate($clickPoint)
    {
        $data = explode('|', $clickPoint);
        if(empty($data))
        {
            return $result;
        }
        $coordinate = array();
        $point_coordinate = array();
        $eastlng = '';
        $westlng = '';
        $southlat = '';
        $northlat = '';
        $data = array_map(array($this, 'myPointFun'), $data);
        $this->compensateMile = 0;
        foreach($data as $key=>$point)
        {
            // 获取边界坐标
            empty($eastlng) && $eastlng = $point[0];
            empty($westlng) && $westlng = $point[0];
            empty($southlat) && $southlat = $point[1];
            empty($northlat) && $northlat = $point[1];
            $eastlng = $eastlng < $point[0] ? $point[0] : $eastlng;
            $westlng = $westlng > $point[0] ? $point[0] : $westlng;
            $southlat = $southlat > $point[1] ? $point[1] : $southlat;
            $northlat = $northlat < $point[1] ? $point[1] : $northlat;
            if(isset($data[$key-1]))
            {
//                if($point[2]<=0)
//                {
//                    exit('描点有误，请重新操作');
//                }
                //$coordinate =array_merge($coordinate, $this->getCoordinate($point, $data[$key-1]));

                $point_coordinate = array_merge($point_coordinate, $this->getPointCoordinate($point, $data[$key-1]));
            }
        }
        $arr = [];
        foreach($data as $key=>$point) {
            $arr[$point[3]][] = $point;
        }

//       var_dump($arr);
        foreach ($arr as $kx=>$vx) {
            $coordinateTmp = [];
            $i =0;
            foreach($vx as $key=>$point){
                if(isset($vx[$key-1]))
                {
                    if($point[2]<=0)
                    {
                        exit('描点有误，请重新操作');
                    }
                    $coordinateTmp =array_merge($coordinateTmp, $this->getCoordinate($point, $vx[$key-1]));
                    $i = 1;
                }
            }
            $i == 1 && $coordinate[] = $coordinateTmp;
        }
//        var_dump($coordinate);
//        $southWestPoint = '[{"lng":"'.$westlng.'","lat":"'.$southlat.'"}]';
//        $northEastPoint = '[{"lng":"'.$eastlng.'","lat":"'.$northlat.'"}]';
        $southWestPoint = '{"lng":"'.$westlng.'","lat":"'.$southlat.'"}';
        $northEastPoint = '{"lng":"'.$eastlng.'","lat":"'.$northlat.'"}';
        return compact('coordinate','point_coordinate','southWestPoint','northEastPoint');
    }
    /**
     * 根据两点坐标及距离，生成坐标
     * @param nowPoint 当前点坐标
     * @param prevPoint 上一点坐标
     * @param perMilNumber 每公里打点数量
     * @param offset 偏移量
     */
    private function getCoordinate($nowPoint, $prevPoint, $perMilNumber = 200, $offset = 0.000008)
    {
        $result = array();
        $distance = $nowPoint[2];
        $lngrate = round(($nowPoint[0]-$prevPoint[0])/$distance/$perMilNumber, 8);
        $latrate = round(($nowPoint[1]-$prevPoint[1])/$distance/$perMilNumber, 8);
        if($lngrate >0)
        {
            for ($i=$prevPoint[0],$j = $prevPoint[1]; $i <= $nowPoint[0]; $i+=$lngrate, $j+=$latrate) {
                //$result[] = '{lng":"'.round($i+rand(-1, 1)/1*$offset, 6).'","lat":"'.round($j+rand(-1, 1)/1*$offset, 6).'"}';
                $result[] = array("lng"=>round($i+rand(-1, 1)/1*$offset, 6),"lat"=>round($j+rand(-1, 1)/1*$offset, 6));
            }
        }
        elseif($lngrate < 0)
        {
            for ($i=$prevPoint[0],$j = $prevPoint[1]; $i >= $nowPoint[0]; $i+=$lngrate, $j += $latrate) {
                //$result[] = '{"lng":"'.round($i+rand(-1, 1)/1*$offset, 6).'","lat":"'.round($j+rand(-1, 1)/1*$offset, 6).'"}';
                $result[] = array("lng"=>round($i+rand(-1, 1)/1*$offset, 6),"lat"=>round($j+rand(-1, 1)/1*$offset, 6));
            }
        }
        else
        {
            for ($i=$prevPoint[0],$j = $prevPoint[1]; $j <= $nowPoint[1]; $j+=$latrate) {
                //$result[] = '{"lng":"'.round($i+rand(-1, 1)/1*$offset, 6).'","lat":"'.round($j+rand(-1, 1)/1*$offset, 6).'"}';
                $result[] = array("lng"=>round($i+rand(-1, 1)/1*$offset, 6),"lat"=>round($j+rand(-1, 1)/1*$offset, 6));
            }
        }
        return $result;
    }
    /**
     * 根据两点坐标及距离，生成整公里坐标
     * @param nowPoint 当前点坐标
     * @param prevPoint 上一点坐标
     */
    private function getPointCoordinate($nowPoint, $prevPoint)
    {
        $compensateMile = $this->compensateMile;
        $result = array();
        $distance = $nowPoint[2];
        if($compensateMile + $distance < 1)
        {
            $this->compensateMile = $compensateMile + $distance;
            return $result;
        }
        $lngrate = round(($nowPoint[0]-$prevPoint[0]) / $distance, 8);
        $latrate = round(($nowPoint[1]-$prevPoint[1]) / $distance, 8);
        for ($i=$prevPoint[0]+(1-$compensateMile)*$lngrate,$j=$prevPoint[1]+(1-$compensateMile)*$latrate,$count =0;$distance+$compensateMile-$count>=1; $i+=$lngrate, $j += $latrate, $count++) {
            $result[] = '{"lng":"'.round($i, 6).'","lat":"'.round($j, 6).'"}';
        }
        $this->compensateMile =($compensateMile+$distance)*100%100/100;
        return $result;
    }
    private function myPointFun($v)
    {
        return explode(',', $v);
    }
    /**
     * 所有用户的跑步记录
     */
    public function doallRunData()
    {
        $t = common::request('t','G',1);
        $p = common::request('p', 'G', 1);
        $uid = common::request('uid','G');
        $order_id = common::request('order_id','G');
        $did = common::request('did','G');
        $overSpeed = common::request('overSpeed', 'G', 0);
        $overSpeed = intval($overSpeed);
        $overSpeed > 1 && $overSpeed = 1;


        $abnorData=common::$abnorData;
        $r_table = !empty($t) && in_array($t, array(1, 2)) ? 'r_data' : 'r_visitor_data';

        $where_clause = ' where 1 ';

        if(empty($uid)){
            $where_clause .= $overSpeed > 0 ? " and overSpeed <> 0 ": '';
        }else{
            $where_clause .= $overSpeed > 0 ? " and overSpeed <> 0 and uid=$uid ": " and uid=$uid";
        }

        if($t == 2)
        {
            $where_clause .= " and run_mood!='' ";
        }
        
        if($order_id){
            $where_clause .= " and d.order_id='{$order_id}'";
        }

        $did && $where_clause .= " and d.did='{$did}'";

        $num = $this->db->getOne("select count(did) from $r_table d $where_clause");
        //分页
        require FILE . 'lib/page.class.php';
        $listNum = 10;
        $page = new Page($num, $listNum);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);

        $start = ($p - 1) * $listNum;
        if($r_table == 'r_data')
            $runData = $this->db->getAll("select d.*,de.coordinate from $r_table as d left join r_data_ext de on d.did=de.did $where_clause order by d.did desc limit $start, $listNum");
        else
            $runData = $this->db->getAll("select * from $r_table d $where_clause order by did desc limit $start, $listNum");

        if($runData)
        {
            foreach ($runData as &$v)
            {
                $uncompress = @gzuncompress($v['coordinate']);
                $v['coordinate'] = $uncompress === false ? $v['coordinate'] : $uncompress;
                $runner = in_array($t, array(1, 2)) ? $this->load('client')->getUserInfo($v['uid']) : $this->load('client')->getVisitorInfo($v['vid']);
                $v['nickname'] = $runner['nickname'];
            }
        }

        $this->view->assign('runData', $runData);
        $this->view->assign('type', $t);
        $this->view->assign('abnorData', $abnorData);
        $this->view->assign('overSpeedUrl', stripos($_SERVER['REQUEST_URI'], '&overSpeed=1') ? $_SERVER['REQUEST_URI'] : $_SERVER['REQUEST_URI'].'&overSpeed=1');
        $this->view->display('showHistory');
    }

    /**
    * 显示路径地图
    **/
    public function doviewRoute()
    {
        $t = common::request('t','G',1);
        $did = common::request('did','G');
        if(empty($did)) return;

//        $r_table = !empty($t) && $t==1 ? 'r_data' : 'r_visitor_data';
        if(!empty($t) && $t==1 ) {
            $runData = $this->db->getRow("select d.did, d.city, de.coordinate, d.point_coordinate, d.detail_speed from r_data d left join r_data_ext de on d.did=de.did where d.did= $did");
        } else {
            $runData = $this->db->getRow("select did, city, coordinate, point_coordinate, detail_speed from r_visitor_data where did= $did");
            
        }

        if (!empty($runData)) {
            $runData['coordinate'] = empty($runData['coordinate']) ? '[]' : $runData['coordinate'];
            $uncompress = @gzuncompress(base64_decode($runData['coordinate']));

            if ($uncompress !== false) {
                $uncompress =  stripslashes($uncompress);
                $runData['coordinate'] = $uncompress;
            }
            
            $runData['point_coordinate'] = empty($runData['point_coordinate']) ? '[]' : $runData['point_coordinate'];

            $runData['detail_speed'] = empty($runData['detail_speed']) ? '[]' : $runData['detail_speed'];
            $coordinate = json_decode($runData['coordinate'],true);
            $data = [];
            $i = 0;
            foreach($coordinate as $k=>$val){
                if(isset($val['lat'])){
                    $data[$i][] = $val;
                }else{
                    foreach($val as $item){
                        $data[$i][] = $item;
                    }
                    $i++;
                }
            }
            $runData['coordinate'] = json_encode($data);
        }
    $this->view->assign('runData', $runData);
    $this->view->display('viewRoute');
    }

    /**
     * 删除跑步记录
     */
    public function dodelRunData()
    {
        $did = common::request('did', 'G');
        $t = common::request('t', 'G');
        $id = common::request('id', 'G');

        if($did)
        {
            $result = $this->load('run')->deleteUserRunDataBYDid($did, $t, $id);
            if($result['is_success'] && $t == 1)
            {
              // 群组跑步数据
              $this->load('group')->deleteRunData($id,array('did' => $result['did'], 'updatetime' => $result['updatetime']));
            }
            header("Location:{$_SERVER['HTTP_REFERER']}\n");
            exit;
        } else
        {
            exit('查无此记录');
        }
    }
    /**
     * 恢复已删除跑步记录
     */
    public function dorecoverRunData()
    {
        $did = common::request('did', 'G');
        $t = common::request('t', 'G');
        $id = common::request('id', 'G');
        if ($did)
        {
            $result = $this->load('run')->recoverRunDataRunDataBYDid($did, $t, $id);
            header("Location:{$_SERVER['HTTP_REFERER']}\n");
            exit;
        } else
        {
            exit('查无此记录');
        }
    }

    /**
     * 标记正常某次跑步异常数据
     *
     */
    public function doabToNorData()
    {
        $did = common::request('did', 'G');
        $t = common::request('t', 'G');
        $id = common::request('id', 'G');

        $uid = $t == 1 ? $id : 0;
        if(!$uid)
        {
            exit('参数错误');
        }

        if($did)
        {

            $rel = $this->load('run')->addAbdateTnor($did);

             header("Location:{$_SERVER['HTTP_REFERER']}\n");
             exit;
        }
        else
        {
            exit('参数错误');
        }

    }




    /**
     * 修正游客跑步数据
     */
    public function docolVisitorRunData()
    {
        set_time_limit(180);
        $vids = $this->db->getAll('select vid, old_uid from r_visitor order by vid ASC');
        foreach ($vids as $key => $visistor)
        {
            $vid = $visistor['vid'];
            $old_uid = $visistor['old_uid'];

            $dids = $this->db->getCol("select did from r_visitor_data where vid = {$vid} and is_delete = 0 group by order_id");
            if(empty($dids) || count($dids) ==1)
            {
                continue;
            }
            $dbIn = $this->load('pushController')->db_create_in($dids, 'did not');

            $this->db->delDataTable('r_visitor_data', $dbIn ." and vid = {$vid}");

            $totalData = $this->db->getRow("select vid, sum(mileage) as total_mileage, sum(elapsedtime) as total_elapsedtime, sum(calorie) as total_calorie, count(*) as total_rate from r_visitor_data where vid = '{$vid}'");

            $this->load('client')->saveVisitorInfo($vid, $totalData);

            // 更新用户里程排名
            if($old_uid > 1)
            {
                $this->load('run')->setClientMileageStandingsRank($old_uid, $totalData['total_mileage']);
            }
        }
        exit(date('Y-m-d H:i:s'));
    }
    /**
     * 跑步记录页面
     */
    public function dostanding()
    {
        $result = $this->load('run')->getMileageStandingTopInfo(100);

        $this->view->assign('data', $result);
        $this->view->display('standing');
    }

    /**
     * 删除排名
     */
    public function dodelStd()
    {
        $uid = common::request('uid', 'G');
        //删除排名
        if ($uid)
        {
            $rank = $this->redis->zrevrank(REDIS_PREFIX . 'StandingsMileage', $uid);
            if ($rank !== FALSE)
            {
                if ($this->redis->zrem(REDIS_PREFIX . 'StandingsMileage', $uid))
                {
                    echo 'uid为' . $uid . '删除成功';
                }
            }
        }
    }

    /*
      public function doclearAll()
      {
      $keys = $this->redis->keys(REDIS_PREFIX."*");
      $result = $this->redis->del($keys);
      if($result){
      echo 'clear all redis data is ok!';
      }
      }

      public function doclearStd()
      {
      $rank = $this->redis->zrem(REDIS_PREFIX . 'StandingsMileage', 1568);
      if($rank){
      echo '删除成功';
      }
      }

      public function dogetStd()
      {
      $rankList = $this->redis->ZREVRANGE(REDIS_PREFIX . 'StandingsMileage', 0, -1);
      var_dump($rankList);
      }
     */
    public function doupdateUser()
    {
        $this->view->display('admin');
    }

    /*-------------------------------------- 内容设置 ----------------------------------- */

    /*
    * 广告设置
    */
    public function doadsSetting()
    {
        $type = common::request('type', 'G','edit');
        $publishChannel = common::$publishChannel;
        $channel_list = array();
        foreach ($publishChannel as $key => $channel_name) {
            if($this->getAdsSettings($key))
            {
                $channel_list[$key] = $channel_name;
            }
        }
        if($type != 'add')
        {
            $channel = common::request('channel', 'G', 'index');
            $data = array();
            $ads_url = array();
            $channelAdsInfo = $this->getAdsSettings($channel);
            if($channelAdsInfo)
            {
                $img_suf = "?time=".time(); // 解决更新图片后需要刷新页面才显示新图片的问题
                $pre_rul = $this->load('qiniu')->getQNHost();
                $ads_url['apple'] = $pre_rul.$channelAdsInfo['ads_name'].'_apple.jpg'.$img_suf;
                $ads_url['android'] = $pre_rul.$channelAdsInfo['ads_name'].'_android.jpg'.$img_suf;
                $ads_url['apple_4'] = $pre_rul.$channelAdsInfo['ads_name'].'_apple_4.jpg'.$img_suf;
                $ads_url['apple_5'] = $pre_rul.$channelAdsInfo['ads_name'].'_apple_5.jpg'.$img_suf;
                $ads_url['apple_6'] = $pre_rul.$channelAdsInfo['ads_name'].'_apple_6.jpg'.$img_suf;
                $ads_url['apple_6P'] = $pre_rul.$channelAdsInfo['ads_name'].'_apple_6P.jpg'.$img_suf;
                $ads_url['android_s'] = $pre_rul.$channelAdsInfo['ads_name'].'_android_s.jpg'.$img_suf;
                $ads_url['android_m'] = $pre_rul.$channelAdsInfo['ads_name'].'_android_m.jpg'.$img_suf;
                $ads_url['android_l'] = $pre_rul.$channelAdsInfo['ads_name'].'_android_l.jpg'.$img_suf;
            }
            else{
                common::go("index.php?c=admin&a=adsSetting&type=add\n");
            }
        }
        else{
            $channel = '';
            $channelAdsInfo = array('ads_desc'  => '',
                                    'splasher_name' => '',
                                    'ads_url' => '',
                                    'show_count' => 3,
                                    'duration_time' => 5,
                                    'daily_words' => '',
                                    'a_start_time' => time(),
                                    'a_end_time' => time()+7*86400,
                                    'ads_is_show' => 1,
                            );
            $ads_url = array();
            $ads_url['apple_4'] = $ads_url['apple_5'] = $ads_url['apple_6'] = $ads_url['apple_6P'] = $ads_url['android_s'] = $ads_url['android_m'] = $ads_url['android_l'] = '';
        }

        $this->view->assign('channel', $channel);
        $this->view->assign('action', $type == 'add' ? 'insert' : 'update');
        $this->view->assign('channel_list', $channel_list);
        $this->view->assign('channelAdsInfo', $channelAdsInfo);
        $this->view->assign('ads_url', $ads_url);
        $this->view->assign('publishChannel', $publishChannel);
        $this->view->display('advertisement');
    }
    /*
    *   添加或更新闪屏广告设置
    */
    public function doupdateAdsSetting()
    {
        $channel = common::request('channel', 'P');
        if(!array_key_exists($channel, common::$publishChannel))
        {
            echo '无法识别渠道类型，请检查后重试';
            exit();
        }
        $action = common::request('action', 'P');
        $ads_is_show = common::request('ads_is_show', 'P',0);
        $splasher_name = common::request('splasher_name', 'P');
        $show_count = common::request('show_count', 'P', 0);
        $duration_time = common::request('duration_time', 'P',5);
        $ads_name = $channel.'_img';
        $ads_desc = common::request('ads_desc', 'P');
        $ads_url = common::request('ads_url', 'P', '', true);
        $daily_words = common::request('daily_words', 'P', '', true);
        $a_start_time = common::request('a_start_time', 'P');
        $a_end_time = common::request('a_end_time', 'P');
        $ads_is_click = !empty($ads_url) ? 1 : 0;
        $a_start_time = strtotime($a_start_time);
        $a_end_time = strtotime($a_end_time);
        if(empty($a_start_time) || empty($a_end_time) || $a_start_time >= $a_end_time)
        {
            exit('开始和结束时间不能为空,且开始时间要大于结束时间');
        }
        if(empty($splasher_name))
        {
            exit('闪屏图名称不能为空');
        }
        $ads_name .= $a_start_time;
        $config_type = $channel.'_ads';
        $channelAdsInfo = compact('ads_is_show','splasher_name','ads_name','ads_desc','ads_url','show_count','duration_time', 'daily_words', 'ads_is_click', 'a_start_time', 'a_end_time');
        foreach ($channelAdsInfo as $key => $value)
        {
            if($action == 'update')
            {
                $this->db->update("update r_config set value = '".$value."' where name = '".$key."' and config_type = '{$config_type}'");
            }
            else{
                $this->db->insert("INSERT INTO r_config (`name`, `value`, `config_type`) VALUES ('{$key}', '{$value}', '{$config_type}')");
            }
            $this->redis->hmset(REDIS_PREFIX.'Splasher_'.$channel, $channelAdsInfo);
        }

        $uploadimg = array('apple','android','apple_4','apple_5','apple_6','apple_6P','android_l','android_m','android_s');

        require FILE . 'lib/image.class.php';
        foreach ($uploadimg as $inputname)
        {
            if($_FILES[$inputname]['size'] == 0)
            {
                continue;
            }
            $fix = str_replace(array('image/', 'jpeg'), array('', 'jpg'), $_FILES[$inputname]['type']);
            if($fix != 'jpg')
            {
                echo '图片类型规定为：jpg';
                exit;
            }

            if($_FILES[$inputname]['size'] > 120*1024)
            {
                echo '有图片尺寸超过了120KB！';
                exit;
            }
            
            $this->load('qiniu')->uploadQiNiuImg($inputname, $ads_name.'_'.$inputname);
        }
        header("Location:index.php?c=admin&a=adsSetting&channel=".$channel."\n");
        exit;
    }
    /*
    *   获取广告设置
    */
    private function getAdsSettings($channel='index')
    {
        $result = array();
        if(!array_key_exists($channel, common::$publishChannel))
        {
            return $result;
        }
        $result = $this->redis->hgetall(REDIS_PREFIX.'Splasher_'.$channel);
        if(empty($result))
        {
            $config_type = $channel.'_ads';
            $data= $this->db->getall("select name, value from r_config where config_type = '{$config_type}'");
            if($data)
            {
                foreach ($data as $key => $v) {
                    $result[$v['name']] = $v['value'];
                }
                $this->redis->hmset(REDIS_PREFIX.'Splasher_'.$channel, $result);
            }
        }
        return $result;
    }
    /*-------------------------------------- 内容设置 ----------------------------------- */


    /*-------------------------------------- 好友关系 Start ----------------------------------- */

    public function dofriendsRelationships()
    {
        $status = common::request('status','G', '2');
        $p = common::request('p', 'G', 1);

        if (!in_array($status, array(0,1,2,3)))
        {
            return;
        }

        //分页
        require FILE . 'lib/page.class.php';
        $listNum = 30;
        $num = 1000;
        $page = new Page($num, $listNum);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);
        $start = ($p - 1) * $listNum;

        $sql = "select u.uid, u.nickname, u.header, A.counts from (SELECT uid, count(1) as counts FROM r_add_friend where status=$status group by uid) A inner join r_user u on A.uid = u.uid order by counts desc limit $start, $listNum";
        $friendsData = $this->db->getAll($sql);

        $this->view->assign('friendsData', $friendsData);
        $this->view->display('friendsRelationships');
    }

    public function dofriendsList()
    {
        $uid = common::request('uid','G');
        $friendsList = $this->load('friends')->getFriendsList($uid);
        $newfriends = $this->load('friends')->getPushFriend($uid, true);

        $this->view->assign('friendsList', $friendsList);
        $this->view->assign('newfriends', $newfriends);

        $this->view->display('friendsList');
    }

    /*-------------------------------------- 好友关系 End ----------------------------------- */


    /*-------------------------------------- 数据报表 ----------------------------------- */

    //跑步记录统计
    public function dorunRecordReport()
    {
        $days = common::request('day','G', '7');
        $days = $days < 30 ? $days : '7';
        $sql = "select  FROM_UNIXTIME(addtime, '%Y-%m-%d') as day, count(1) as  counts, sum(round(mileage,3)) as mileage, sum(round(elapsedtime,3))/3600 as elapstime from (
            select  addtime, mileage, elapsedtime from r_data
                where addtime >= UNIX_TIMESTAMP(date_sub(CURDATE(), INTERVAL $days day))
            union
            select  addtime, mileage, elapsedtime from r_visitor_data
                where addtime >= UNIX_TIMESTAMP(date_sub(CURDATE(), INTERVAL $days day))
            ) as temp
            group by day  order by day desc";

        $runData = $this->db->getAll($sql);
        $this->view->assign('runData', $runData);
        $this->view->display('runRecordReport');
    }

    //DAU统计
    public function dodauReport()
    {
        $this->view->display('dauReport');
    }

    //绑定用户情况统计
    public function dobindUserReport()
    {
        $days = common::request('days','G', '7');
        $days = $days <= 30 ? $days : '7';

        $sql = "SELECT channel,count(1) total FROM r_social_user r where is_bind = 1 group by channel ";
        $userData = $this->db->getAll($sql);

        $detailSQL = "select d,
                sum(if(type='QQ',total,0)) as QQ,
                sum(if(type='Weibo',total,0)) as Weibo,
                sum(if(type='Wechat',total,0)) as Wechat,
                sum(if(type='renren',total,0)) as Renren,
                sum(if(type='phone',total,0)) as phone,
                sum(if(type='Others',total,0)) as Others from
                    (SELECT FROM_UNIXTIME(create_time,'%Y-%m-%d') d, count(1) total,
                    case channel when 2 then 'QQ' when 3 then 'Weibo' when 4 then 'Wechat' when 5 then 'renren' when 6 then 'phone' else 'Others' end as type
                    FROM r_social_user
                    where create_time >= UNIX_TIMESTAMP(date_sub(CURDATE(), INTERVAL $days day))
                group by d,channel) A group by d order by d desc;";
        $detailUserData = $this->db->getAll($detailSQL);

        $this->view->assign('userData', $userData);
        $this->view->assign('detailUserData', $detailUserData);
        $this->view->display('bindUserReport');
    }

    public function doregUserReport()
    {
        $days = common::request('days','G', '7');
        $days = $days <= 30 ? $days : '7';
        $sql = "select d,
                    sum(if(type='Android',total,0)) as Android,
                    sum(if(type='iOS',total,0)) as iOS,
                    sum(if(type='Others',total,0)) as Others from
                        (SELECT FROM_UNIXTIME(addtime,'%Y-%m-%d') d, count(1) total,
                        case c.client_type when 1 then 'Android' when 2 then 'iOS' else 'Others' end as type
                        FROM r_user r left join r_client c on r.cid=c.cid
                        where r.addtime >= UNIX_TIMESTAMP(date_sub(CURDATE(), INTERVAL $days day))
                        group by d,client_type) A
                group by d order by d desc;";
        $userData = $this->db->getAll($sql);
        $this->view->assign('userData', $userData);
        $this->view->display('regUserReport');
    }
    // 注册渠道报表
    public function doregChannelReport()
    {
        $startDate = common::request('startDate', 'R',date("Y-m-d",strtotime("-3 day")));
        $endDate = common::request('endDate', 'R',date("Y-m-d"));
        // $fromChannel = common::request('fromChannel', 'R','');

        $search = compact('startDate', 'endDate');
        $startTime = strtotime($startDate);
        $endTime = strtotime($endDate) + 86400;

        $channelData = array();
        $days = $this->db->getCol("select FROM_UNIXTIME(addtime, '%Y-%m-%d') as m from r_user where addtime >= '{$startTime}' and addtime < '{$endTime}' group by m order by addtime DESC");
        $channels = $this->db->getCol("select distinct(IF(fromChannel != '',fromChannel, 'index')) as fromChannel from r_user where addtime >= '{$startTime}' and addtime < '{$endTime}'");
        if($days)
        {
            foreach ($days as $value) {
                $data = $this->db->getAll("select IF(fromChannel != '',fromChannel, 'index') as fromChannel, count(*) as total from r_user where FROM_UNIXTIME(addtime, '%Y-%m-%d')= '{$value}' group by fromChannel");
                foreach ($data as $key => $v) {
                    $data[$v['fromChannel']] = $v['total'];
                    unset($data[$key]);
                }
                foreach ($channels as $channel) {
                    $channelData[$value][$channel] = isset($data[$channel]) ? $data[$channel] : 0;
                }
            }
        }

        $this->view->assign('search', $search);
        $this->view->assign('channels', $channels);
        $this->view->assign('channelInfo', common::$publishChannel);
        $this->view->assign('channelData', $channelData);
        $this->view->display('regChannelReport');
    }
    /*-------------------------------------- 用户好友建立报表 ----------------------------------- */
    public function douserFriendsReport()
    {
        $days = common::request('days','G', '7');

        $days = intval($days);
        // $days = $days <= 30 ? $days : '7';
        $userFriendsData = array();
        $reqsql = "select FROM_UNIXTIME(add_time,'%Y-%m-%d') as d,
                    floor(count(*)/2) as req from r_add_friend
                    where add_time >= UNIX_TIMESTAMP(date_sub(CURDATE(), INTERVAL $days day))
                    and status != 0
                    group by d order by d desc";
        $reqFriendsData = $this->db->getAll($reqsql);

        $sucsql = "select FROM_UNIXTIME(last_update,'%Y-%m-%d') as d,
                    floor(count(*)/2) as become from r_add_friend
                    where last_update >= UNIX_TIMESTAMP(date_sub(CURDATE(), INTERVAL $days day))
                    and status = 2
                    group by d order by d desc";
        $sucFriendsData = $this->db->getAll($sucsql);

        foreach ($reqFriendsData as $k =>$req) {
            $reqFriendsData[$req['d']] = $req;
            unset($reqFriendsData[$k]);
        }
        foreach ($sucFriendsData as $k =>$suc) {
            $sucFriendsData[$suc['d']] = $suc;
            unset($sucFriendsData[$k]);
        }
        foreach ($reqFriendsData as $kr =>$req) {
            $userFriendsData[$req['d']] = $req;
            $userFriendsData[$req['d']]['become'] = isset($sucFriendsData[$kr]) ? $sucFriendsData[$kr]['become'] : 0;
        }
        foreach ($sucFriendsData as $ks =>$suc) {
            if(!isset($userFriendsData[$ks]))
            {
                $userFriendsData[$suc['d']] = $suc;
                $userFriendsData[$suc['d']]['req'] = 0;
            }
        }
        $this->view->assign('userFriendsData', $userFriendsData);
        $this->view->display('userFrReport');
    }
    /*-------------------------------------- 资讯点击统计 ----------------------------------- */
    public function donewsClickReport()
    {
        $p = common::request('p', 'G', 1);
        $news_id = common::request('news_id', 'R', '');
        $startTime = common::request('startTime', 'R', '');
        $endTime = common::request('endTime', 'R' ,'');

        $parameter = '';//分页跳转的参数
        $search =compact('news_id', 'startTime', 'endTime');
        $query = ' where 1';
        $query .= empty($news_id) ? '' : " and news_id = '{$news_id}'";
        $query .= empty($startTime) ? '' : " and add_time >= '".strtotime($startTime)."'";
        $query .= empty($endTime) ? '' : " and add_time <= '".strtotime($endTime)."'";

        $parameter = '&'.urldecode(http_build_query($search, NULL, '&'));

        $countSql = 'select count(*) from (select news_id from r_news_click '.$query.' group by news_id) as a';
        //empty($date) && $countSql .=' group by news_id';
        $num = $this->db->getOne($countSql);
        //分页
        require FILE . 'lib/page.class.php';
        $listNum = 15;
        $page = new Page($num, $listNum, $parameter);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);

        $start = ($p - 1) * $listNum;
        /*
        if(!empty($date))
        {
            $sql = 'select *, (andCount + iosCount) as totalClick from r_news_click '. $query;
        }
        else
        {
            $sql = 'select news_id, add_time, sum(andCount+iosCount) as totalClick,sum(andCount) as andCount,sum(andCCount) as andCCount,sum(andPushCount) as andPushCount, sum(andPushCCount) as andPushCCount,sum(iosCount) as iosCount,sum(iosCCount) as iosCCount,sum(iosPushCount) as iosPushCount,sum(iosPushCCount) as iosPushCCount from r_news_click '. $query .' group by news_id';
        }
        */
            $sql = 'select news_id, add_time, sum(andCount+iosCount) as totalClick,sum(andCount) as andCount,sum(andCCount) as andCCount,sum(andPushCount) as andPushCount, sum(andPushCCount) as andPushCCount,sum(iosCount) as iosCount,sum(iosCCount) as iosCCount,sum(iosPushCount) as iosPushCount,sum(iosPushCCount) as iosPushCCount from r_news_click '. $query .' group by news_id';
        $sql .= " order by add_time DESC, news_id DESC limit $start, $listNum";
        $clickData = $this->db->getAll($sql);

        $this->view->assign('search', $search);
        $this->view->assign('clickData', $clickData);
        $this->view->display('newsClickReport');
    }

    //跑步有道 - 社区发帖数报表
    public function doboardTopicReport()
    {
        $sql = "select from_unixtime(a.add_time, '%Y-%m-%d') newsDate,
                count(if(b.boardId='hotans', 1,null)) as 'hotans',
                count(if(b.boardId='showtime', 1,null)) as 'showtime',
                count(if(b.boardId='rungear', 1,null)) as 'rungear',
                count(if(b.boardId='injury', 1,null)) as 'injury',
                count(if(b.boardId='beginner', 1,null)) as 'beginner',
                count(if(b.boardId='healthy', 1,null)) as 'healthy',
                count(if(b.boardId='runmood', 1,null)) as 'runmood',
                count(if(b.boardId='events', 1,null)) as 'events',
                count(if(b.boardId='training', 1,null)) as 'training',
                count(if(b.boardId='marathon', 1,null)) as 'marathon',
                count(a.news_id) as total
                from r_news a inner join r_boardPost b on a.news_id=b.news_id
                group by newsDate desc limit 0,30";

        $topicData = $this->db->getAll($sql);
        $this->view->assign('topicData', $topicData);
        $this->view->display('boardTopicReport');
    }




    /*-------------------------------------- 数据报表 ----------------------------------- */

    /*
    * 资讯标签管理
    */
    public function doaddNewsTag()
    {
        require_once FILE.'../web/static/kindeditor/php/JSON.php';
        $json = new Services_JSON();

        $tag = common::request('tag', 'G');
        $tag = trim($tag);
        $message = '';
        if(!empty($tag))
        {
            if($this->redis->sismember(REDIS_PREFIX . 'NewsTags', $tag))
            {
                $message = '该标签已存在';
            }
            else
            {
                $message = $this->redis->sadd(REDIS_PREFIX . 'NewsTags', $tag) ? '' : '添加失败了，快报警！';
            }
        }
        else
        {
            $message = '你是在调戏我吗？为毛添加空标签';
        }
        echo $json->encode(array('message' => $message, 'tag' => $tag));
        exit;
    }
    /*-------------------------------------- kindeditor 上传图片 ----------------------------------- */
    public function douploadKindEditorImg()
    {
        require_once FILE.'../web/static/kindeditor/php/JSON.php';

        //定义允许上传的文件扩展名
        $ext_arr = array(
            'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp')
            // 'flash' => array('swf', 'flv'),
            // 'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
            // 'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2'),
        );
        //最大文件大小
        $max_size = 1000000;
        $file_size = $_FILES['imgFile']['size'];

        //检查文件大小
        if ($file_size > $max_size) {
            $this->alert("上传文件大小超过限制。");
        }
        $dir_name = empty($_GET['dir']) ? 'image' : trim($_GET['dir']);
        //获得文件扩展名
        $file_name = $_FILES['imgFile']['name'];
        $temp_arr = explode(".", $file_name);
        $file_ext = array_pop($temp_arr);
        $file_ext = trim($file_ext);
        $file_ext = strtolower($file_ext);
        //检查扩展名
        if (in_array($file_ext, $ext_arr[$dir_name]) === false) {
            $this->alert("上传文件扩展名是不允许的扩展名。\n只允许" . implode(",", $ext_arr[$dir_name]) . "格式。");
        }
        $new_file_name = 'PostImg_'.md5(time().$file_name);
        $file_url = $this->load('qiniu')->uploadQiNiuImg('imgFile', $new_file_name);
        empty($file_url) && $this->alert('上传失败');
        header('Content-type: text/html; charset=UTF-8');
        $json = new Services_JSON();
        echo $json->encode(array('error' => 0, 'url' => $file_url));
        exit;
    }
    /*-------------------------------------- kindeditor 上传图片结束 ----------------------------------- */

    /*-------------------------------------- 资讯列表开始 ----------------------------------- */
    public function donewsList()
    {
        $p = common::request('p', 'G', 1);

        $newsdata = $this->load('news')->getNewsList(0, 'next', 10, $p);

        $this->view->assign('newsdata', $newsdata);
        $this->view->display('newsList');
    }
    /*-------------------------------------- 资讯结束 ----------------------------------- */

    /*-------------------------------------- 评论列表开始 ----------------------------------- */
    public function docommentList()
    {
        $news_id = common::request('news_id', 'G', 0);
        $page = common::request('p', 'G', 1);
        $tips = NULL;
        $hotComment = array();
        $allcomment = array();
        if(empty($news_id))
        {
            $tips = '参数不正确';
        }
        else
        {
            $default=$this->redis->hget(REDIS_PREFIX.'defaultAns',$news_id);
            $allcomment = $this->load('news')->getNewsCommentList($news_id,'all',0,'',10,$page);
        }
        $this->view->assign('news_id',$news_id);
        $this->view->assign('tips', $tips);
        $this->view->assign('default',$default);
        // $this->view->assign('hotComment', $hotComment);
        $this->view->assign('allcomment', $allcomment);
        $this->view->display('commentList');
    }
    /*-------------------------------------- 评论列表结束 ----------------------------------- */
      /*-------------------------------------- 装备评论列表开始 ----------------------------------- */
  public function dogearcommentList()
    {
        $gearId = common::request('gearId', 'G', 0);
        $page = common::request('p', 'G', 1);
        $tips = NULL;
        $hotComment = array();
        $allcomment = array();
        if(empty($gearId))
        {
            $tips = '参数不正确';
        }
        else
        {
            $allcomment = $this->load('gear')->getGearCommentList($gearId ,'', 0, '',10,$page);
        }

        foreach ($allcomment as & $v)
        {
            if(!empty($v['image'])){
                $v['image'] = json_decode($v['image'], true);
                $v['image'] = array_slice($v['image'], 0);
            }else{
                $v['image'] = array();
            }
        }



        $this->view->assign('tips', $tips);
        $this->view->assign('gearId', $gearId);
        $this->view->assign('hotComment', $hotComment);
        $this->view->assign('allcomment', $allcomment);
        $this->view->display('gearcommentList');
    }
    /*-------------------------------------- 装备评论列表结束 ----------------------------------- */
    /**
     * 所有评论列表
     */
    public function doallComments()
    {
        $uid = common::request('uid','G');
        $p = common::request('p', 'G',1);
        require FILE . 'lib/page.class.php';
        
        $where = " where 1 ";
        if($uid){
            $nickname = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$uid, 'nickname');
            $where .= " and uid=$uid or (father_id != 0 and comment_content like '%$nickname%')";
        }
        $num = $this->db->getone('select count(*) from r_news_comment'.$where);
        $offset = 20;
        $page = new Page($num, $offset);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);

        $start = ($p-1) * $offset;
        $sql = "select * from r_news_comment $where order by add_time DESC"." limit {$start}, {$offset}";
        $allcomment = $this->db->getAll($sql);
        if($allcomment)
        {
            foreach ($allcomment as $k => & $comment) {
                $comment['floor'] = $num - ($p-1) * $offset-$k;
                $comment['nickname'] = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$comment['uid'], 'nickname');
                $comment['header'] = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$comment['uid'], 'header');
            }
        }
        $this->view->assign('tips', '');
        $this->view->assign('default',0);
        $this->view->assign('allcomment', $allcomment);
        $this->view->display('commentList');
    }
    /*-------------------------------------- 添加评论开始 ----------------------------------- */
    public function doaddNewsComment()
    {
        $news_id = common::request('news_id', 'R');
        $type = common::request('type', 'G', 'add');
        $p = common::request('p','G',1);
        $boardId = common::request('boardId','G',-1);
        $news_info = $this->load('news')->getNewsInfo($news_id);
        if(empty($news_id) || empty($news_info))
        {
            exit('参数不完整');
        }
        $message = '';
        $commentInfo = array();
        if($type != 'insert')
        {
            $commentInfo = array(
                            'comment_id' => 0,
                            'news_id' => $news_id,
                            'father_id' => 0,
                            'uid' => '',
                            'comment_content' => '',
                            'comment_img' => '',
                            'thumb_img' => '',
                            'nickname' => '',
                            'header' => '',
                            'add_time' => time(),
                    );
        }
        else
        {
            $news_id = common::request('news_id', 'P');
            $uid = common::request('uid', 'P');
            $nickname = common::request('nickname', 'P');
            $header = common::request('header', 'P');
            $comment_content = common::request('comment_content', 'P');
            $add_time = common::request('add_time', 'P');
            $is_show = 1;
            $userInfo = $this->load('client')->getUserInfo($uid);
            if(empty($userInfo)){
                $this->_go('该用户不存在！');
                exit;
            }
            $url = 'index.php?c=admin&a=postList&p='.$p."&boardId=$boardId";
            $nickname = $userInfo['nickname'];
            $header = $userInfo['header'];
            if(empty($news_id) || empty($uid) || empty($comment_content) || empty($add_time))
            {
                $message = '参数不完整';
            }
            else
            {
                if($this->load('badwords')->check($comment_content))
                {
                    $message = '评论内容有不和谐字符，你懂的。';
                }
                else
                {
                    $father_id = common::request('father_id',"P",0);
                    if($father_id > 0){
                        $tid = common::request('tid','P');
                        $name = common::request('name','P');
                        $msg = '回复<at href="joggers://profile/'.$tid.'">'.$name.'</at>';
                        $comment_content = $msg.$comment_content;
                        $url = "index.php?c=admin&a=commentList&news_id={$news_id}&p=$p&boardId=$boardId";
                    }
                    $comment_img = $this->load('qiniu')->uploadQiNiuImg('comment_img', 'PC'.md5($news_id.'/'.time().common::getHashStr(6)));
                    $img_size = empty($comment_img) ? array() : getimagesize($_FILES['comment_img']['tmp_name']);
                    if(!empty($img_size))
                    {
                        $thumbInfo = $this->load('news')->getThumbInfo($img_size[0], $img_size[1]);
                        extract($thumbInfo);
                        $thumb_img = empty($thumb_img) ? $comment_img : $comment_img .'?imageMogr2/thumbnail/'.$thumb_img;
                    }
                    else
                    {
                        $thumb_size = '0x0';
                        $thumb_img = '';
                    }
                    $add_time = strtotime($add_time);
                    $commentInfo = compact('news_id','father_id','uid','comment_content','add_time','is_show', 'comment_img','thumb_img','thumb_size');
                    $new_comment_id = $this->db->insertRowTable('r_news_comment', $commentInfo);
                    if($new_comment_id)
                    {
                        $postInfo = $this->load('bbs')->getPostInfo($news_id);
                        // 评论楼层
                        $this->redis->zadd(REDIS_PREFIX.'NewsComFloor_'.$news_id, $new_comment_id, $new_comment_id);
                        // 增加正能量
                        $this->load('client')->userEnergyChange($uid, 'comment',$new_comment_id);
                        if($uid != $postInfo['uid'])
                        {
                            $this->load('bbs')->addUnReadMsg($postInfo['uid'], array('msgType'=>1, 'sponsor'=>array('uid'=>$uid,'comment_id'=>$new_comment_id), 'quote'=>array('news_id'=>$news_id,'comment_id'=>'0')));
                        }
                        $this->redis->HINCRBY(REDIS_PREFIX. 'NewsInfo_'.$news_id, 'total_comment', 1);
                        //$this->db->update("update r_news set total_comment = total_comment+1 where news_id = '{$news_id}'");
                        $this->load('bbs')->update(['total_comment'=>'?+1','news_id'=>$news_id]);
                        if($postInfo['is_show'] != 0)
                        {
                            // 更新版块最热列表
                            if(!empty($postInfo['board']))
                            {
                                foreach ($postInfo['board'] as $board) {
                                    $this->redis->ZADD(REDIS_PREFIX.'BoardPostList'.$board['boardId'].'_Hot', time(), $news_id);
                                }
                            }
                            // 更新标签最热列表
                            if(!empty($postInfo['tag']))
                            {
                                foreach ($postInfo['tag'] as $tag) {
                                    $this->redis->ZADD(REDIS_PREFIX.'TagPostList'.$tag['tagId'].'_Hot', time(), $news_id);
                                }
                            }
                        }
                    }
                    $message = '添加评论成功';
                }
            }
        }

        if($message){
            $this->_go($message,$url);
            exit;
        }
        $this->view->assign('p',$p);
        $this->view->assign('boardId',$boardId);
        $this->view->assign('message', $message);
        $this->view->assign('commentInfo', $commentInfo);
        $this->view->display('commentInfo');
    }
/*-------------------------------------- 添加评论结束 ----------------------------------- */

/*-------------------------------------- 添加装备评论开始 ----------------------------------- */
    public function doaddGearComment()
    {
        $gearId = common::request('gearId', 'R');
        $type = common::request('type', 'G', 'add');
        $gearInfo = $this->load('gear')->getGearInfo($gearId);
        if(empty($gearId) || empty($gearInfo))
        {
            exit('参数不完整');
        }
        $message = '';
        $commentInfo = array();
        if($type != 'insert')
        {
            $commentInfo = array(
                            'commentId' => 0,
                            'gearId' => $gearId,
                       //   'fatherId' = > 0,
                            'nickname' => '',
                            'header' => '',
                            'uid' => '',
                            'content' => '',
                            'image' => '',
                            'thumbImg' => '',
                            'lights' => '',
                            'score' => '',
                            'isShow' => '',
                            'addTime' => time(),
                    );
        }
        else
        {
            $gearId = common::request('gearId', 'P');
            $uid = common::request('uid', 'P');
            $nickname = common::request('nickname', 'P');
            $header = common::request('header', 'P');
            $score = common::request('score', 'P');
            $content = common::request('content', 'P');
            $addTime = common::request('addTime', 'P');
            $isShow = 1;
          if(empty($gearId) || empty($uid) ||  empty($content) || empty($addTime))
           //  if(empty($gearId) || empty($uid) ||   empty($content) || empty($addTime))
            {
                $message = '参数不完整';
            }
            else
            {
                if($this->load('badwords')->check($content))
                {
                    $message = '评论内容有不和谐字符，你懂的。';
                }
                else
                {
                    $father_id = 0;
                    $image= $this->load('qiniu')->uploadQiNiuImg('image', 'PC'.md5($gearId.'/'.time().common::getHashStr(6)));
                    $img_size = empty($comment_img) ? array() : getimagesize($_FILES['comment_img']['tmp_name']);
                    if(!empty($img_size))
                    {
                        $thumbInfo = $this->load('news')->getThumbInfo($img_size[0], $img_size[1]);
                        extract($thumbInfo);
                        $thumb_img = empty($thumb_img) ? $comment_img : $comment_img .'?imageMogr2/thumbnail/'.$thumb_img;
                    }
                    else
                    {
                        $thumb_size = '0x0';
                        $thumb_img = '';
                    }
                    $addTime = strtotime($addTime);
                    $commentInfo = compact('commentId','gearId','uid', 'content','addTime','image', 'thumbImg', 'lights', 'isShow','score');
                    $gear_comment_id = $this->db->insertRowTable('r_gear_comment', $commentInfo);
                    if($gear_comment_id)
                    {
                         $gearInfo = $this->load('gear')->getGearInfo($gearId);
                        // 评论楼层
                         $this->redis->zadd(REDIS_PREFIX.'GearComFloor_'.$gearId, $gear_comment_id, $gear_comment_id);
                         $floor = $this->redis->zrank(REDIS_PREFIX.'GearComFloor_'.$gearId, $gear_comment_id)+1;

                        // // 增加正能量
                        // $this->load('client')->userEnergyChange($uid, 'comment',$new_comment_id);
                        // if($uid != $postInfo['uid'])
                        // {
                        //     $this->load('bbs')->addUnReadMsg($postInfo['uid'], array('msgType'=>1, 'sponsor'=>array('uid'=>$uid,'comment_id'=>$new_comment_id), 'quote'=>array('news_id'=>$news_id,'comment_id'=>'0')));
                        // }
                        // $this->redis->HINCRBY(REDIS_PREFIX. 'NewsInfo_'.$news_id, 'total_comment', 1);
                        // $this->db->update("update r_news set total_comment = total_comment+1 where news_id = '{$news_id}'");
                        // if($postInfo['is_show'] != 0)
                        // {
                        //     // 更新版块最热列表
                             if(!empty($gearInfo['board']))
                            {
                                 foreach ($gear['board'] as $board) {
                                    $this->redis->ZADD(REDIS_PREFIX.'BoardPostList'.$board['boardId'].'_Hot', time(), $gearId);
                                 }
                            }
                             // 更新标签最热列表
                                if(!empty($gearInfo['tag']))
                            {
                                 foreach ($gearInfo['tag'] as $tag) {
                                    $this->redis->ZADD(REDIS_PREFIX.'TagPostList'.$tag['tagId'].'_Hot', time(), $gearId);
                                }
                            }
                        // }
                        $this->redis->HINCRBY(REDIS_PREFIX.'GearInfo_'.$gearId, 'comments', 1);
                        $this->db->update("update r_gear set comments = comments+1 where gearId = '{$gearId}'");
                    }
                    $message = "<a href='index.php?c=admin&a=gearcommentList&gearId=$gearId'>添加评论成功, 返回</a>";
                }
            }
        }
        if($message) exit($message);

        $this->view->assign('userlist', $this->db->getAll('select uid,nickname from r_user where is_robot=1'));
        $this->view->assign('message', $message);
        $this->view->assign('commentInfo', $commentInfo);
        $this->view->display('gearcommentInfo');
    }
    /*-------------------------------------- 添加装备评论结束 ----------------------------------- */
    /**
     * 添加VIP用户
     */
    public function docheckVipUser()
    {
        require_once FILE.'../web/static/kindeditor/php/JSON.php';
        $json = new Services_JSON();

        $uid = common::request('uid', 'G');
        $type = common::request('type', 'G',0);
        $message = '';
        $nickname = '无法获取用户昵称';
        $header = '无法获取用户头像';
        $isRealUser = $this->db->getrow("select nickname, header from r_user where uid = '{$uid}'");
        if($isRealUser)
        {
            $isVip = $this->redis->sismember(REDIS_PREFIX . 'VipUserList', $uid);
            $nickname = $isRealUser['nickname'];
            $header = $isRealUser['header'];
            if(!$type && !$isVip){
                $message = '该用户不是VIP用户';
            }

        }
        else
        {
            $message = '该用户不存在，请检查';
        }
        echo $json->encode(array('message' => $message, 'nickname' => $nickname, 'header' => $header));
        exit;
    }
    /**
     * 添加VIP用户
     */
    public function doaddVipUser()
    {
        require_once FILE.'../web/static/kindeditor/php/JSON.php';
        // header('Content-type: text/html; charset=UTF-8');
        $json = new Services_JSON();

        $user = common::request('user', 'G');
        $error = 0;
        $message = '';
        $isRealUser = $this->db->getOne("select uid from r_user where uid = '{$user}' or nickname = '{$user}'");
        if($isRealUser)
        {
            $isExist = $this->redis->sismember(REDIS_PREFIX . 'VipUserList', $isRealUser);
            if($isExist)
            {
                $error = 1;
                $message = '该用户已是VIP用户，请勿重复添加';
            }
            else
            {
                $this->redis->sadd(REDIS_PREFIX . 'VipUserList', $isRealUser);
                $message = '添加成功';
            }
        }
        else
        {
            $error = 2;
            $message = '该用户不存在，请检查后重新添加';
        }
        echo $json->encode(array('err' => $error, 'message' => $message));
        exit;
    }
    /**
     * 删除VIP用户
     */
    public function dodelVipUser()
    {
        $uid = common::request('uid', 'G');
        $isRealUser = $this->db->getOne("select uid from r_user where uid = '{$uid}'");
        if($isRealUser)
        {
            $isExist = $this->redis->sismember(REDIS_PREFIX . 'VipUserList', $uid);
            if($isExist)
            {
                $this->redis->srem(REDIS_PREFIX . 'VipUserList', $uid);
                $message = "移除成功";
            }
            else
            {
                $message = '该用户不是VIP用户';
            }
        }
        else
        {
            $message = '该用户不存在，请检查';
        }
        header("Location:index.php?c=admin&a=supermanList&message=".$message."\n");
        exit;
    }
    /**
     * VIP用户列表
     */
    public function dosupermanList()
    {
        $message = common::request('message', 'G', '');
        $uids = $this->redis->smembers(REDIS_PREFIX . 'VipUserList');

        $userData = array();
        if($uids)
        {
            $dbUid = $this->load('push')->db_create_in($uids, 'uid');
            $userData = $this->db->getAll('select * from r_user where '.$dbUid);
        }

        $this->view->assign('userData', $userData);
        $this->view->assign('message', $message);
        $this->view->display('supermanList');
    }
    /**
     * 添加预设背景图
     */
    public function douserBgInfo()
    {
        $type = common::request('type', 'R', 'add');
        $background_id = common::request('background_id', 'G', 0);
        $tips = common::request('tips', 'G', '');

        $redisKey = REDIS_PREFIX.'UserBg_';
        if($type == 'add')
        {
            $bgInfo = array(
                        'background_id' => 0,
                        'background_name' => '',
                        'background_url' => '',
                        'short_url' => '',
                        'sort_order' => 1,
                        'is_show' => 1,
                        'add_time' => time()
                );
        }
        elseif($type == 'insert')
        {
            $background_name = common::request('background_name', 'P');
            $is_show = common::request('is_show', 'P');
            $sort_order = common::request('sort_order', 'P');
            $add_time = time();
            $background_url = $this->load('qiniu')->uploadQiNiuImg('background_img', 'backgroundurl_'.$add_time);
            $short_url = $this->load('qiniu')->uploadQiNiuImg('thumb_img', 'backgroundshorturl_'.$add_time);
            if(empty($background_name) || empty($background_url) || empty($short_url))
            {
                exit('参数不完整');
            }
            $bgInfo = compact('background_name', 'is_show', 'background_url', 'short_url', 'sort_order', 'add_time');
            $background_id = $this->db->insertRowTable('r_bg_list', $bgInfo);
            if($background_id)
            {
                $redisData = compact('background_id','background_name','background_url','short_url');
                $this->redis->hmset($redisKey.$background_id, $redisData);
                $is_show == 1 && $this->redis->zadd(REDIS_PREFIX . 'SortBackGround', $sort_order, $background_id);

                $tips = "噢吼，背景添加成功！<a href='?c=admin&a=userBgInfo&type=edit&background_id=".$background_id."'>看看我的大作</a>";
            }
        }
        elseif($type == 'edit')
        {
            $bgInfo = $this->load('client')->getUserBgInfo($background_id);
            empty($bgInfo) && $bgInfo = $this->db->getRow("select * from r_bg_list where background_id = {$background_id} limit 1");
            if(!$bgInfo)
            {
                $tips = '参数不正确，找不到对应背景信息';
            }
        }
        elseif($type == 'update')
        {
            $background_id = common::request('background_id', 'P');
            $background_name = common::request('background_name', 'P');
            $is_show = common::request('is_show', 'P');
            $sort_order = common::request('sort_order', 'P');
            $timeNow = time();
            $background_url = $this->load('qiniu')->uploadQiNiuImg('background_img', 'backgroundurl_'.$timeNow);
            $short_url = $this->load('qiniu')->uploadQiNiuImg('thumb_img', 'backgroundshorturl_'.$timeNow);
            if(empty($background_name))
            {
                exit('参数不完整');
            }
            $bgInfo = compact('background_id','background_name', 'is_show', 'sort_order');
            !empty($background_url) && $bgInfo['background_url'] = $background_url;
            !empty($short_url) && $bgInfo['short_url'] = $short_url;
            $result = $this->db->updateRowTable('r_bg_list', $bgInfo);
            if($result)
            {
                $redisData = compact('background_id','background_name','background_url','short_url', 'sort_order');
                if(empty($background_url))
                {
                    unset($redisData['background_url']);
                }
                if(empty($short_url))
                {
                    unset($redisData['short_url']);
                }
                $this->redis->hmset($redisKey.$background_id, $redisData);
                if($is_show == 1)
                {
                    $this->redis->zadd(REDIS_PREFIX . 'SortBackGround', $sort_order, $background_id);
                }
                else
                {
                    $this->redis->zrem(REDIS_PREFIX . 'SortBackGround',$background_id);
                }
                $tips = "噢吼，背景修改成功！<a href='?c=admin&a=userBgInfo&type=edit&background_id=".$background_id."'>看看我的大作</a>";
                $tips .= "&nbsp;&nbsp;&nbsp; <a href='?c=admin&a=userBgInfo&type=add'>继续添加背景</a>";
            }
            else
            {
                $tips = "肿么了，怎么会操作失败……";
            }
        }
        else
        {
            exit('wrong');
        }

        $this->view->assign('tips', $tips);
        $this->view->assign('type', $type);
        $this->view->assign('bgInfo', $bgInfo);
        $this->view->display('userBgInfo');
    }
    /**
     * 用户个人中心预设背景图列表
     */
    public function douserBgList()
    {
        $bgList = $this->db->getAll('select * from r_bg_list order by sort_order DESC');

        $this->view->assign('bgList', $bgList);
        $this->view->display('userBgList');
    }
    /**
     * 城市天气列表
     */
    public function doweatherList()
    {
        $s = common::request('s','R');
        $query = ' where 1';
        $parameter = '';//分页跳转的参数
        $search = array('cityId'=>'', 'cityName'=>'','provinceName'=>'');
        if ($s == "search")
        {
            $cityId = common::request('cityId', 'R', '');
            $cityName = common::request('cityName', 'R', '');
            $provinceName = common::request('provinceName', 'R', '');

            $search = compact('cityId', 'cityName','provinceName');

            $parameter = compact('s','cityId', 'cityName','provinceName');
            $parameter = '&'.urldecode(http_build_query($parameter, NULL, '&'));

            $query .= empty($cityName) ? "":" and  city like '%$cityName%' ";
            $query .= empty($cityId) ? "" : " and city_id_new=$cityId ";
            $query .= empty($provinceName) ? "" : " and pro like '%$provinceName%' ";
        }
        $p = common::request('p', 'G', 1);
        $num = $this->db->getOne('select count(city_id_new) from r_city '.$query);
        //分页
        require FILE . 'lib/page.class.php';
        $listNum = 20;
        $page = new Page($num, $listNum, $parameter);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);

        $start = ($p - 1) * $listNum;
        $sql = "select city_id_new from r_city".$query." order by id ASC limit $start,$listNum";
        $citylist = $this->db->getCol($sql);
        $cityWeatherData = array();
        if($citylist)
        {
            foreach ($citylist as & $city_id) {
                $weather =  $this->redis->get(REDIS_PREFIX . 'weather_'. $city_id);
                $weather && $cityWeatherData[] = json_decode($weather, true);
            }
        }
        $this->view->assign('cityWeatherData', $cityWeatherData);
        $this->view->assign('search', $search);
        $this->view->display('cityWeatherList');
    }
    /*-------------------------------------- 操作评论开始 ----------------------------------- */
    public function doeidtNewsComment()
    {
        $comment_id = common::request('comment_id', 'G', 0);
        $news_id = common::request('news_id', 'G', 0);
        if (!empty($comment_id))
        {
            $type = common::request('type', 'G');
            $is_show = $type == 'hidden' ? 0 : 1;
            $extraSql = $type == 'hidden' ? 'total_comment = total_comment -1' :'total_comment = total_comment+1';
            $nowStatus = $this->db->getOne("select is_show from r_news_comment where comment_id = '{$comment_id}'");
            if($is_show == $nowStatus)
            {
                exit('参数有误');
            }
            $query = $this->db->query("update r_news_comment set is_show = '{$is_show}' where comment_id = '{$comment_id}' and news_id='{$news_id}'");
            if($query)
            {
                $this->db->query('update r_news set '.$extraSql." where news_id = '{$news_id}'");

                if($is_show == 1)
                {
                    //$this->db->update("update r_news set total_comment = total_comment+1 where news_id = '{$news_id}'");
                    $this->load('bbs')->update(['total_comment'=>'?+1','news_id'=>$news_id]);
                }
                else
                {
                    $this->db->update("update r_news set total_comment = total_comment-1 where news_id = '{$news_id}'");
                    //$this->load('bbs')->update(['total_comment'=>'?-1','news_id'=>$news_id]);
                }
                $increby = $is_show == 1 ? 1 : -1;
                $this->redis->HINCRBY(REDIS_PREFIX. 'NewsInfo_'.$news_id, 'total_comment', $increby);
                $this->load('bbs')->updateHotComment($news_id);
            }
        }
        $jumpUrl = $_SERVER['HTTP_REFERER'];
        header("Location:$jumpUrl\n");
        exit;
    }
    /*-------------------------------------- 操作评论结束 ----------------------------------- */

      /*-------------------------------------- 操作装备评论开始 ----------------------------------- */
   public function doeidtGearComment()
    {
        $type = common::request('type', 'G');
        $comment_id = common::request('commentId', 'G', 0);
        $gearId = common::request('gearId', 'G', 0);
        if (!empty($comment_id))
        {

            $isShow = $type == 'hidden' ? 0 : 1;
            $extraSql = $type == 'hidden' ? 'comments = comments -1' :'comments = comments+1';
            $nowStatus = $this->db->getOne("select isShow from r_gear_comment where commentId = '{$comment_id}'");
            if($isShow == $nowStatus)
            {
                exit('参数有误');
            }
            $query = $this->db->query("update r_gear_comment set isShow = '{$isShow}' where commentId = '{$comment_id}' and gearId='{$gearId}'");
            if($query)
            {
                $this->db->query('update r_gear set '.$extraSql." where gearId = '{$gearId}'");

                if($isShow == 1)
                {
                    $this->db->update("update r_gear set comments = comments+1 where gearId = '{$gearId}'");
                }
                else
                {
                    $this->db->update("update r_gear set comments = comments-1 where gearId = '{$gearId}'");
                }
                $increby = $isShow == 1 ? 1 : -1;
                $this->redis->HINCRBY(REDIS_PREFIX. 'GearInfo_'.$gearId, 'comments', $increby);
                //$this->load('bbs')->updateHotComment($news_id);
            }
        }
        $jumpUrl = $_SERVER['HTTP_REFERER'];
        header("Location:$jumpUrl\n");
        exit;
    }
    /*-------------------------------------- 操作装备评论结束 ----------------------------------- */


    /*-------------------------------------- 显示设置违禁词 ----------------------------------- */
    public function dosetbadwords()
    {
        $type = common::request('type', 'P','');
        if(!empty($type))
        {
            $isUserNameBadWords = $type == 'u';

            $badwords = common::request($isUserNameBadWords ? 'userBadwords' : 'badwords', 'P','');
            $badwords = str_replace(array("'", '"'), array('', ''), $badwords);

            $badWorldLists = explode('|', $badwords);

            $badWorldLists = array_map('trim', $badWorldLists);
            $badWorldLists = array_unique($badWorldLists);
            $badWorldLists = array_filter($badWorldLists);

            if($isUserNameBadWords)
            {
                $result = $this->load('badwords')->setUserNameBadWords($badWorldLists);
            }
            else
            {
                $result = $this->load('badwords')->setBadWords($badWorldLists);
            }
            
            $tips = $result ? '修改成功':'修改失败';
            header("Location:index.php?c=admin&a=setbadwords&tips=".$tips."&time=".time()."\n");
            exit;
        }

        $badWorldLists = $this->load('badwords')->getBadWords();
        $badwordsString = implode('|', $badWorldLists);
        $tips = common::request('tips', 'G', '');

        $usernameBadwords = $this->load('badwords')->getUserNameBadWords();
        $userNameBadwordsString = implode('|', $usernameBadwords);

        $this->view->assign('userNameBadwordsString', $userNameBadwordsString);
        $this->view->assign('badwordsString', $badwordsString);
        $this->view->assign('tips', $tips);
        $this->view->display('badwords');
    }

    private function alert($msg)
    {
        require_once FILE.'../web/static/kindeditor/php/JSON.php';
        header('Content-type: text/html; charset=UTF-8');
        $json = new Services_JSON();
        echo $json->encode(array('error' => 1, 'message' => $msg));
        exit;
    }
    /*
    * 添加或推送任务
    */
    public function domsgPushInfo()
    {
        $handletype = common::request('handletype','', 'add');
        $tips = common::request('tips', 'G', '');
        $detail = array();

        $msgTypeUrlArray =array('0' =>array('name' => '资讯详情',
                                            'url' => 'joggers://news/{news_id}',
                                            'message' => '轻声提醒您，不要忘记填入资讯ID哦（o^o）'
                                            ),
                                '1' =>array('name' => '资讯列表',
                                            'url' => 'joggers://newslist/',
                                            'message' => ''
                                            ),
                                '2' =>array('name' => '开始跑步',
                                            'url' => 'joggers://run/',
                                            'message' => ''
                                            )
                            );
        if($handletype == 'add')
        {
            $detail = array('msg_id'=> 0,
                            'title' =>'',
                            'android_message' => '',
                            'android_test' => '',
                            'ios_message' => '',
                            'ios_test' => '',
                            // 'push_type' => '',
                            'status' => 0,
                            'url' => '',
                            'add_time' => '',
                            'finish_time' => '',
                            'device_type' => 0,
                            'send_time' => time(),
                            'is_sound' => 0,
                            'gender' => 0,
                            'city' => '',
                            'uids' => ''
                            );
        }
        elseif($handletype == 'edit')
        {
            $msg_id = common::request('msg_id', 'G', 0);
            if($msg_id)
            {
                $detail = $this->db->getRowTable('r_msg_push', array(), "msg_id = {$msg_id}");
                if($detail)
                {
                    $detail['add_time'] && $detail['add_time'] = date('Y-m-d H:i:s', $detail['add_time']);
                    $detail['finish_time'] && $detail['finish_time'] = date('Y-m-d H:i:s', $detail['finish_time']);
                    $detail['android_test'] = $this->redis->hget(REDIS_PREFIX . 'PushTest', $msg_id.'_and');
                    $detail['ios_test'] = $this->redis->hget(REDIS_PREFIX . 'PushTest', $msg_id.'_ios');
                    empty($detail['send_time']) && $detail['send_time'] = time();
                }
            }
            else
            {
                $tips = '参数不完整';
                $detail = array();
            }
        }
        elseif($handletype == 'insert')
        {
            $device_type = common::request('device_type', 'P',0);
            $is_sound = common::request('is_sound', 'P',0);

            $title = common::request('title', 'P','');
            $android_message = common::request('android_message', 'P','');
            $ios_message = common::request('ios_message', 'P','');
            $android_test = common::request('android_test', 'P','');
            $ios_test = common::request('ios_test', 'P','');
            $url = common::request('url', 'P','');
            $send_time = common::request('send_time', 'P');
            $gender = common::request('gender','P',0);
            $city = common::request('city','P');
            $uids = trim(common::request('uids','P'));
            $send_time = strtotime($send_time);
            $send_time < time() && $send_time = time();
            $add_time = time();
            $status = 0;

            switch ($device_type)
            {
                case 0:
                    if(empty($url) || empty($title) || empty($android_message) || empty($ios_message))
                    {
                        $tips = '参数不完整';
                    }
                    break;
                case 1:
                    if(empty($url) || empty($title) || empty($android_message))
                    {
                        $tips = '参数不完整';
                    }
                    break;
                case 2:
                    if(empty($url) || empty($ios_message))
                    {
                        $tips = '参数不完整';
                    }
                    break;
                default:
                    $tips = '无效参数';
                    break;
            }
            if(empty($tips))
            {
                $insertArray = compact('title','android_message', 'ios_message', 'url','device_type', 'is_sound', 'add_time', 'send_time','gender','city','uids');
                $msg_id = $this->db->insertRowTable('r_msg_push', $insertArray);
                if($msg_id)
                {
                    $tips = "噢吼，推送任务添加成功！<a href='?c=admin&a=msgPushInfo&handletype=edit&msg_id=".$msg_id."'>查看推送详情</a>";
                    !empty($android_test) && $this->redis->hset(REDIS_PREFIX . 'PushTest', $msg_id.'_and', $android_test);
                    !empty($ios_test) && $this->redis->hset(REDIS_PREFIX . 'PushTest', $msg_id.'_ios', $ios_test);
                }
                else
                {
                    $tips = '噢,添加失败了，快去检查一下出了什么问题吧！';
                }
            }
        }
        elseif($handletype == 'update')
        {
            $msg_id = common::request('msg_id', 'P',0);
            $device_type = common::request('device_type', 'P',0);
            $is_sound = common::request('is_sound', 'P',0);

            $title = common::request('title', 'P','');
            $android_message = common::request('android_message', 'P','');
            $ios_message = common::request('ios_message', 'P','');
            $url = common::request('url', 'P','');
            $send_time = common::request('send_time', 'P');
            $send_time = strtotime($send_time);
            $send_time < time() && $send_time = time();
            $tips = '';
            $android_test = common::request('android_test', 'P','');
            $ios_test = common::request('ios_test', 'P','');
            $gender = common::request('gender','P');
            $city = common::request('city','P');
            $uids = trim(common::request('uids','P'));
            if(empty($msg_id))
            {
                $tips = '参数不完整';
            }
            else
            {
                $status = $this->db->getone("select status from r_msg_push where msg_id = {$msg_id} limit 1");
                if($status != 0)
                {
                    $tips = "该任务已在推送中或是推送完成，不能进行此操作";
                }
                else
                {
                    switch ($device_type)
                    {
                        case 0:
                            if(empty($url) || empty($title) || empty($android_message) || empty($ios_message))
                            {
                                $tips = '参数不完整';
                            }
                            break;
                        case 1:
                            if(empty($url) || empty($title) || empty($android_message))
                            {
                                $tips = '参数不完整';
                            }
                            break;
                        case 2:
                            if(empty($url) || empty($ios_message))
                            {
                                $tips = '参数不完整';
                            }
                            break;
                        default:
                            $tips = '无效参数';
                            break;
                    }
                }
            }

            if(empty($tips))
            {
                // if(!$checkNewsTitle)
                // {
                //     echo "<script type='text/javascript'>alert('".$tips."')</script>";
                //     echo '<script language="javascript">history.go(-1);</script>';
                // }
                $insertArray = compact('msg_id','title','android_message', 'ios_message', 'url','device_type', 'is_sound','send_time','gender','city','uids');
                if($this->db->updateRowTable('r_msg_push', $insertArray))
                {
                    if(!empty($android_test))
                    {
                        $this->redis->hset(REDIS_PREFIX . 'PushTest', $msg_id.'_and', $android_test);
                    }
                    else
                    {
                        $this->redis->del(REDIS_PREFIX . 'PushTest', $msg_id.'_and');
                    }
                    if(!empty($ios_test))
                    {
                        $this->redis->hset(REDIS_PREFIX . 'PushTest', $msg_id.'_ios', $ios_test);
                    }
                    else
                    {
                        $this->redis->del(REDIS_PREFIX . 'PushTest', $msg_id.'_ios');
                    }
                    $tips = "噢吼，推送任务更新成功！<a href='?c=admin&a=msgPushInfo&handletype=edit&msg_id=".$msg_id."'>查看推送详情</a>";
                }
                else
                {
                    $tips = '噢,更新失败，快去检查一下出了什么问题吧！';
                }
            }
        }

        $this->view->assign('handletype', $handletype);
        $this->view->assign('msgTypeUrlArray', $msgTypeUrlArray);
        $this->view->assign('detail', $detail);
        $this->view->assign('tips', $tips);
        $this->view->display('msgPushInfo');
    }
    /*
    * 推送任务列表
    */
    public function domsgPushList()
    {
        //删除操作
        $ope = common::request('operate', 'P');
        
        if ($ope == 'del') {
            $pid = common::request('id', 'P');
            
            if ($pid) {
                $this->db->delDataTable('r_msg_push', 'msg_id=' . $pid . ' and status=0');
                exit(json_encode(['code' => 0, 'msg' => '操作成功']));
            } else {
                exit(json_encode(['code' => 1, 'msg' => '操作失败']));
            }
        }
        
        $p = common::request('p', 'G', 1);
        $offset = 10;

        $num = $this->db->getone('select count(msg_id) from r_msg_push');

        //分页
        require FILE . 'lib/page.class.php';
        $page = new Page($num, $offset);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);

        $start = ($p - 1) * $offset;
        $sql = "select * from r_msg_push order by add_time DESC limit $start,$offset";
        $pushData = $this->db->getall($sql);

        $this->view->assign('pushData', $pushData);
        $this->view->display('msgPushList');
    }


    public function doInstrMsgList(){

        $p = common::request('p', 'G', 1);
        $offset = 10;
        $num = $this->db->getone('select count(id) from r_message_instr');

        //分页
        require FILE . 'lib/page.class.php';
        $page = new Page($num, $offset);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);

         $start = ($p - 1) * $offset;
        $sql = "select * from r_message_instr order by sort ASC limit $start,$offset";
        $instrContent = $this->db->getAll($sql);

        $this->view->assign('data', $instrContent);
        $this->view->display('instrMsgList');
    }

    public function doclientLog(){
        $s = common::request('s','R','');
        $p = common::request('p', 'G', 1);

        $query = 'where 1';
        $search = array('client_type'=>'',
                        'uid'=>'',
                        'log_type'=>'',
                        'startDate'=>'',
                        'endDate'=>'',
                        'order_id'=>'',
                        'restart_sub_process_count'=>'',
                        'restart_host_process_count'=>'',
                        'is_bress_quit'=>'',
                        'device_type'=>'',
                        'device_release'=>'',
            );
        if($s == "search")
        {
            $client_type = common::request('client_type','R','');
            $uid = common::request('uid','R','');
            $log_type = common::request('log_type','R','');
            //$create_day = common::request('create_day','P','');
            $startDate = common::request('startDate','R','');
            $endDate = common::request('endDate','R','');
            $order_id = common::request('order_id','R','');
            $restart_sub_process_count = common::request('restart_sub_process_count','R','');
            $restart_host_process_count = common::request('restart_host_process_count','R','');
            $is_bress_quit = common::request('is_bress_quit','R','');
            $device_type = common::request('device_type','R','');
            $device_release = common::request('device_release','R','');
            
            $search = compact('client_type','uid','log_type','startDate','endDate','order_id','restart_sub_process_count','restart_host_process_count','is_bress_quit','device_type','device_release');
            $query.=empty($uid) ? "":" and uid = $uid";
            $query.=empty($client_type) ? "": " and client_type = $client_type";
            $query .= empty($log_type) ? "": " AND log_type = $log_type";
            $query .= empty($startDate) ? "": " AND create_day>=".strtotime($startDate);
            $query .= empty($endDate) ? "": " AND create_day<=".strtotime($endDate);
            !empty($order_id) && $query .= " AND order_id=$order_id";
            switch($restart_sub_process_count){
                case -1:
                    $start = 0;
                    $end = 0;
                    break;
                case 1:
                    $start = 1;
                    $end = 10;
                    break;
                case 10:
                    $start = 10;
                    $end = 50;
                    break;
                case 50:
                    $start = 50;
                    $end = 999;
                    break;
            }
            !empty($restart_sub_process_count) && $query .= " AND restart_sub_process_count between $start and $end";
            switch($restart_host_process_count){
                case -1:
                    $start = 0;
                    $end = 0;
                    break;
                case 1:
                    $start = 1;
                    $end = 10;
                    break;
                case 10:
                    $start = 10;
                    $end = 50;
                    break;
                case 50:
                    $start = 50;
                    $end = 999;
                    break;
            }
            !empty($restart_host_process_count) && $query .= " AND restart_host_process_count between $start and $end";
            if(!empty($is_bress_quit)){
                $is_bress_quit = $is_bress_quit==1 ? 1 : 0;
                $query .= " AND is_bress_quit=$is_bress_quit";
            }
            !empty($device_type) && $query .= " AND device_type='$device_type'";
            !empty($device_release) && $query .= " AND device_release='$device_release'";
            
        }

        $offset = 10;
        $this->in_logDb();
        $num = $this->logDb->getone("select count(lid) from client_odd ".$query);
        // $this->logDb->insertRow('client_odd', $log)
        //分页
        require FILE . 'lib/page.class.php';
        $page = new Page($num, $offset);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);

        $start = ($p - 1) * $offset;
        $sql = "select * from client_odd ".$query." order by lid desc limit $start,$offset";
        $content = $this->logDb->getAll($sql);
        foreach ($content as $key => $v) {
            $content[$key]['create_time'] = date('Y-m-d H:m:s',$v['create_time']);
        }
        $this->view->assign('content', $content);
        $this->view->assign('search', $search);
        $this->view->display('clientLog');
    }
    public function doclientLogContent()
    {
        $lid = common::request('lid','G','');
        $this->in_logDb();
        $content = $this->logDb->getone("select log_content from client_odd where lid = $lid");
        $log_content = gzuncompress(base64_decode($content));
        $content = json_decode($log_content,true);
        $content = json_encode($log_content,true);
        //  $content = str_replace(' ','',$content);
        $content = str_replace('\n','',$content);
        $content = str_replace('\\','',$content);
        $content = substr($content,1,strlen($content)-2);
        $this->view->assign('lid',$lid);
        $this->view->assign('content',$content);
        $this->view->display('clientLogContent');
    }
    public function doInstrMsgInfo(){
        $handleType = common::request('handletype', '');

        switch ($handleType) {
            case 'add':
                $this->view->assign('handletype', "insert");
                $this->view->assign('data', array());
                $this->view->assign('tips', "");
                $this->view->assign('id', "");
                $this->view->display('instrMsgInfo');
                break;
            case 'insert':
                $key = common::request('key', 'P');
                $content = common::request('content', 'P');
                $sort = common::request('sort', 'P');

                $insertArray = compact('key','content','sort');
                $msg_id = $this->db->insertRowTable('r_message_instr', $insertArray);
                if($msg_id){
                    $tips = '噢,添加成功';
                     $content = $this->redis->del(REDIS_PREFIX . "Instr");//hash
                }
                $this->view->assign('tips',$tips);
                $this->view->display('instrMsgInfo');
                break;
            case 'edit':
                $id = common::request('id', 'G');
                $data = $this->db->getRow("select * from r_message_instr where id = '{$id}'");
                $this->view->assign('handletype', "update");
                $this->view->assign('data', $data);
                $this->view->assign('id', $id);
                $this->view->assign('tips', "");
                $this->view->display('instrMsgInfo');
                break;
            case 'update':
                $id = common::request('id', 'p');
                //$key = common::request('key', 'P');
                $content = common::request('content', 'P');
                //$sort = common::request('sort', 'P');

                $updateArray = compact('id','content');
                $msg_id = $this->db->updateRowTable('r_message_instr', $updateArray);
                if($msg_id){
                    $tips = '噢,修改成功';
                     $content = $this->redis->del(REDIS_PREFIX . "Instr");//hash
                }
                $this->view->assign('tips',$tips);
                $this->view->display('instrMsgInfo');
                break;
            case 'del':
                $id = common::request('id', 'p');

                $msg_id = $this->db->delDataTable('r_message_instr', "id = '{$id}'");
                if($msg_id){
                    $tips = '噢,删除成功';
                }
                $this->view->assign('tips',$tips);
                $this->view->display('instrMsgInfo');
                break;
        }

    }

    /*
     * 计算数组中最小的连续N个元素的和
    */
    private function getBestSumValue($data, $length = 5)
    {
        $rel = 0;
        if(empty($data) || !is_array($data))
        {
            return $rel;
        }
        $total_length = count($data);
        if($total_length < $length) return $rel;
        $i = 0;
        foreach ($data as $key => $v) {
            $i += 1;
            if($i >= $length)
            {
                $current = array_sum(array_slice($data, $i-$length, $length, false));
                $rel = $current > $rel ? $current : $rel;
            }
        }
        return $rel;
    }
    /*
     * 根据跑步数据获取用户应获得的勋章
    */
    public function getRunMedal($uid, $runData)
    {
        $medalList = array();
        extract($runData);
        $userInfo = $this->load('client')->getUserInfo($uid);
        if(empty($userInfo) || !isset($target_rate) || !isset($mileage) || !isset($updatetime) || !isset($target_rate))
        {
            return $medalList;
        }
        $line = strtotime("next Monday", $updatetime);
        $startDate = date("Ymd", $line - 7*86400);
        $endDate = date("Ymd", $line - 86400);
        $weekRun = $this->db->getOne("select count(*) from r_data_day where uid='{$uid}' and mileage > 0 and date >= '{$startDate}' and date < '{$endDate}'");
        $weekRun += 1;
        if($this->redis->hget(REDIS_PREFIX.'UserMedal_'.$uid, 100) == false)  $medalList[] = 100;
        if($target_rate >= 1 && $mileage > 5)   $medalList[] = 101;
        if($this->redis->hget(REDIS_PREFIX.'UserMedal_'.$uid, 102) == false && $userInfo['total_rate'] >= 2)   $medalList[] = 102;
        if($weekRun == 7 && !$this->redis->sismember(REDIS_PREFIX.'UserMedalEle_'.$uid.'_107', date("YW", $updatetime))) {
            $medalList[] = 107;
        } else if($weekRun == 6 && !$this->redis->sismember(REDIS_PREFIX.'UserMedalEle_'.$uid.'_106', date("YW", $updatetime))) {
            $medalList[] = 106;
        } else if($weekRun == 5 && !$this->redis->sismember(REDIS_PREFIX.'UserMedalEle_'.$uid.'_105', date("YW", $updatetime))) {
            $medalList[] = 105;
        } else if($weekRun == 4 && !$this->redis->sismember(REDIS_PREFIX.'UserMedalEle_'.$uid.'_104', date("YW", $updatetime))) {
            $medalList[] = 104;
        } else if($weekRun == 3 && !$this->redis->sismember(REDIS_PREFIX.'UserMedalEle_'.$uid.'_103', date("YW", $updatetime))) {
            $medalList[] = 103;
        }
        if($mileage > 42 && !$this->redis->sismember(REDIS_PREFIX.'uniqueMedal_119', $uid)) {
            $medalList[] = 119;
        } else if($mileage > 21 && !$this->redis->sismember(REDIS_PREFIX.'uniqueMedal_118', $uid)) {
            $medalList[] = 118;
        } else if($mileage > 10 && !$this->redis->sismember(REDIS_PREFIX.'uniqueMedal_117', $uid)) {
            $medalList[] = 117;
        } else if($mileage > 5 && !$this->redis->sismember(REDIS_PREFIX.'uniqueMedal_116', $uid)) {
            $medalList[] = 116;
        }
        if(date("m-d", $updatetime) == substr($userInfo['birthday'], 5) && $this->redis->sismember(REDIS_PREFIX.'UserMedalEle_'.$uid.'_121', date("Y")) == false)
        {
            $medalList[] = 121;
        }
        if(date("Y-m-d", $updatetime) == date("Y-m-d", strtotime("+1 year", $userInfo['addtime'])) && $this->redis->hget(REDIS_PREFIX.'UserMedal_'.$uid, 120) == false)
        {
            $medalList[] = 120;
        }
        if(date("m-d", $updatetime) == '12-25' && $this->redis->sismember(REDIS_PREFIX.'UserMedalEle_'.$uid.'_122', date("Y", $updatetime)) == false)
        {
            $medalList[] = 122;
        }
        if($this->redis->hget(REDIS_PREFIX.'UserMedal_'.$uid, 123) == false && (date("H", $updatetime) >= 22 || date("H", $updatetime) <= 4))
        {
            $medalList[] = 123;
        }
        if($mileage > $userInfo['max_mileage'])
        {
            $medalList[] = 124;
        }
        if($elapsedtime > $userInfo['max_elapsedtime'])
        {
            $medalList[] = 125;
        }
        return $medalList;
    }
     /*
     * 社区-添加标签
    */
    public function dotagInfo()
    {
        $action = common::request('action','G','add');

        if($action == 'add')
        {
            $tagInfo = array('tagId'    => '',
                         'tagName'  => '',
                         'uid'      => 0,
                         'addTime'  => time(),
                         'isHot'    => 0,
                         'style'    => array()
            );
        }
        else
        {
            $tagId = common::request('tagId','G');
            $tagInfo = $this->load('bbs')->getTagInfo($tagId, true);
            if(empty($tagInfo))
            {
                exit('无效参数');
            }
        }
        $boardList = $this->load('bbs')->getBoardList();
        !isset($tagId) && $tagId = 0;
        foreach ($boardList as & $v) {
            $v['isMem'] = $this->redis->ZSCORE(REDIS_PREFIX.'BoardTagList_'.$v['boardId'], $tagId) !== false ? 1 : 0;
        }
        $this->view->assign('action', $action);
        $this->view->assign('tagInfo', $tagInfo);
        $this->view->assign('boardList', $boardList);
        $this->view->display('tagInfo');
    }
    /*
     * 社区-编辑标签
    */
    public function doeditTag()
    {
        $tagName = common::request('tagName', 'P');
        $uid = common::request('uid', 'P', 0);
        $isHot = common::request('isHot', 'P', 0);
        $boardId = common::request('boardId', 'P');
        $addTime = common::request('addTime', 'P');
        $color = common::request('color', 'P');
        $action = common::request('action', 'R');
        $boardId = $this->load('bbs')->checkBoard($boardId);
        empty($boardId) && $boardId = array();
        $addTime = strtotime($addTime);
        $style = array();
        $color && $style['color'] = $color;
        $style = json_encode($style);
        if(empty($tagName) || empty($action))
        {
            exit('参数不正确');
        }
        $tagInfo = compact('tagName', 'uid','isHot','addTime','style');
        if($action == 'insert')
        {
            if($this->db->getOne("select tagId from r_tag where tagName = '{$tagName}' limit 1"))
            {
                exit('标签已存在');
            }
            $tagId = $this->db->insertRowTable('r_tag', $tagInfo);
            if($tagId)
            {
                $tagInfo['tagId'] = $tagId;
                $this->redis->hmset(REDIS_PREFIX.'TagInfo_'.$tagId, $tagInfo);
                if(!empty($boardId))
                {
                    foreach ($boardId as $v) {
                        $this->db->insertRowTable('r_boardtag', array('boardId' => $v, 'tagId' => $tagId));
                        $this->redis->ZADD(REDIS_PREFIX.'BoardTagList_'.$v, $addTime, $tagId);
                    }
                }
                exit('添加成功');
            }
            else
            {
                exit('操作失败');
            }
        }
        else if($action == 'update')
        {
            $tagId = common::request('tagId', 'P', 0);
            $info = $this->load('bbs')->getTagInfo($tagId);
            if(empty($info))
            {
                exit('参数不正确');
            }
            $oldBoard = $this->db->getCol("select boardId from r_boardtag where tagId = '{$tagId}'");
            sort($boardId);
            sort($oldBoard);
            $tagInfo['tagId'] = $tagId;
            unset($tagInfo['addTime']);
            if($this->db->updateRowTable('r_tag', $tagInfo))
            {
                $this->redis->hmset(REDIS_PREFIX.'TagInfo_'.$tagId, $tagInfo);
                if($boardId != $oldBoard)
                {
                    $reserveBoard = array_intersect($oldBoard, $boardId);
                    foreach ($oldBoard as $value) {
                        if(!in_array($value, $reserveBoard))
                        {
                            $this->db->delDataTable('r_boardtag', "tagId = '{$tagId}' and boardId = '{$value}'");
                            $this->redis->ZREM(REDIS_PREFIX.'BoardTagList_'.$value, $tagId);
                        }
                    }
                    foreach ($boardId as $v) {
                        if(!in_array($v, $reserveBoard))
                        {
                            $this->db->insertRowTable('r_boardtag', array('boardId' => $v,'tagId' => $tagId));
                            $this->redis->ZADD(REDIS_PREFIX.'BoardTagList_'.$v, $addTime,$tagId);
                        }
                    }
                }
            }
            else
            {
                exit('操作失败');
            }
            exit('编辑成功');
        }
    }
    /*
     * 社区-删除标签
    */
    public function dodelTag()
    {
        $tagId = common::request('tagId', 'G', 0);
        $info = $this->load('bbs')->getTagInfo($tagId);
        if(empty($info))
        {
            exit('参数不正确');
        }
        foreach (common::$postListType as $type) {
            if($this->redis->ZCARD(REDIS_PREFIX.'TagPostList'.$tagId.'_'.$type) > 0)
            {
                exit('标签下存在文章，不能删除');
            }
        }
        if($this->db->delDataTable('r_tag', "tagId ='{$tagId}'"))
        {
            $this->redis->del(REDIS_PREFIX.'TagInfo_'.$tagId);
            $oldBoard = $this->db->getCol("select boardId from r_boardtag where tagId = '{$tagId}'");
            if($oldBoard)
            {
                foreach ($oldBoard as $boardId) {
                    $this->db->delDataTable('r_boardtag', "tagId = '{$tagId}' and boardId = '{$boardId}'");
                    $this->redis->ZREM(REDIS_PREFIX.'BoardTagList_'.$boardId, $tagId);
                }
            }
        }
        else
        {
            exit('操作失败');
        }
        exit('成功');
    }
    /*
     * 社区-版块标签
    */
    public function dotagList()
    {
        $p = common::request('p', 'G', 1);
        $listNum = 20;
        $start = ($p-1) * $listNum;
        $num = $this->db->getOne('select count(*) from r_tag');

        require FILE . 'lib/page.class.php';
        $page = new Page($num, $listNum);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);

        $boardList = $this->load('bbs')->getBoardList();
        $tagList = $this->db->getAll("select tagId,tagName, uid from r_tag order by tagId ASC limit $start, $listNum");
        if(!empty($tagList))
        {
            foreach ($tagList as & $value) {
                foreach ($boardList as $v) {
                    $value[$v['boardId']] = $this->redis->ZSCORE(REDIS_PREFIX.'BoardTagList_'.$v['boardId'], $value['tagId']) !== false ? 1 : 0;
                }
            }
        }

        $this->view->assign('boardList', $boardList);
        $this->view->assign('tagList', $tagList);
        $this->view->display('tagList');
    }
    /*
     * 社区-版块管理
    */
    public function doboard()
    {
        $action = common::request('action', 'G','edit');
        $boardId = common::request('boardId', 'G', 'hotans');
        if($action == 'add')
        {
            $boardInfo = array('boardImg' => '', 'boardId' => '', 'boardDesc' => '', 'boardName' => '', 'sortOrder' => '');
            $tagList = array();
        }
        else
        {
            $boardInfo = $this->load('bbs')->getBoardInfo($boardId);
            $tagList = $this->load('bbs')->getBoardTagList($boardId);
        }
        // 版块id
        $boardList = $this->load('bbs')->getBoardList();
        // 版块附加内容
        $addition = $this->load('admin')->getBoardAdditions($boardId);

        $this->view->assign('action', $action);
        $this->view->assign('boardId', $boardId);
        $this->view->assign('boardList', $boardList);
        $this->view->assign('tagList', $tagList);
        $this->view->assign('boardInfo', $boardInfo);
        $this->view->assign('addition', $addition);
        $this->view->display('board');
    }
    /*
     * 社区-编辑版块
    */
    public function doeditBoard()
    {
        $action = common::request('action', 'P');
        $boardId = common::request('boardId', 'P');
        $boardName = common::request('boardName', 'P');
        $boardDesc = common::request('boardDesc', 'P');
        $sortOrder = common::request('sortOrder', 'P');
        $sortOrder = intval($sortOrder);
        if(empty($action) || empty($boardId) || empty($boardName))
        {
            exit('参数不完整');
        }
        if(strlen($boardId) >12 || preg_match('/^\w+$/', $boardId) != 1)
        {
            exit('版块id长度超出限制或格式不正确');
        }
        $boardImg = $this->load('qiniu')->uploadQiNiuImg('boardImg' , 'boardImg'.ucfirst($boardId));
        $boardInfo = compact('boardId','boardName','boardDesc','sortOrder');
        $boardImg && $boardInfo['boardImg'] = $boardImg;
        if($action == 'insert')
        {
            // 添加版块暂无
        }
        else if($action == 'update')
        {
            if($this->load('bbs')->updateBoard($boardInfo) !== false)
            {
                header("Location:index.php?c=admin&a=board&boardId=".$boardId."\n");
                exit;
            }
            else
            {
                exit("操作失败");
            }
        }
        $this->view->display('board');
    }
    /*
     * 社区-焦点图
    */
    public function dofocusImg()
    {
        $urlArr = array(
                    array('name' => '帖子','link' => 'joggers://topic/{topicID}'),
                    array('name' => '板块','link' => 'joggers://topicboard/{boardID}'),
                    array('name' => '标签聚合页面','link' => 'joggers://topictag/{tagID}')
                    );
        $focusImg = $this->load('bbs')->getFocusPic();
        if(empty($focusImg))
        {
            $focusImg = array(array('pictureUrl'=> '', 'linkUrl'=>''));
        }
        $focusImg = array_reverse($focusImg);
        $this->view->assign('urlArr', $urlArr);
        $this->view->assign('focusImg', $focusImg);
        $this->view->display('focusImg');
    }
    /*
     * 社区-焦点图
    */
    public function doeditFocusImg()
    {
        $num = common::request('num','P');
        $num = intval($num);
        $oldFocus = $this->load('bbs')->getFocusPic();
        $oldFocus = array_reverse($oldFocus);
        $newFocus = array();
        $link = common::request('link', 'P');
        $sorts = common::request('sort', 'P');

        for($i = 0; $i <=$num ; $i++){
            if(isset($link[$i]))
            {
                $pictureUrl = $this->load('qiniu')->uploadQiNiuImg('picture_'.$i, md5(time().'bbsfoucspicture_'.$i));
                if(!$pictureUrl && isset($oldFocus[$i]))
                {
                    $pictureUrl = $oldFocus[$i]['pictureUrl'];
                }
                $linkUrl = trim($link[$i]);
                $sort = $sorts[$i] ? $sorts[$i] : 0;
                $pictureUrl && $newFocus[] = compact('pictureUrl','linkUrl','sort');
            }
        }

        usort($newFocus, function($a, $b){if($b['sort'] > $a['sort']){return 1;}elseif($b['sort'] < $a['sort']){return -1;}else{return 0;}});
        $newFocus = array_reverse($newFocus);
        !empty($newFocus) ? $this->redis->set(REDIS_PREFIX.'bbsFocusPic', json_encode($newFocus)) : $this->redis->del(REDIS_PREFIX.'bbsFocusPic');
        common::go('index.php?c=admin&a=focusImg');
    }
    /*
     * 社区-showtime
    */
    public function doshowtime()
    {
        $action = common::request('action', 'R', 'show');
        if($action == 'show')
        {
            $dailyShow = $this->load('bbs')->getDailyShow();
            if(empty($dailyShow))
            {
                for($i=0; $i <=5; $i++)
                {
                    $dailyShow[] = array("imgUrl"   => "",
                                         "news_id"  => "");
                }
            }

            $this->view->assign('dailyShow', $dailyShow);
            $this->view->display('showtime');
        }
        else
        {
            $dailyShow = array();
            $oldShow = $this->load('bbs')->getDailyShow();
            $imgUrl = common::request('imgUrl', 'P');
            $news_id = common::request('news_id', 'P');
            for($i = 0; $i<= 5; $i++)
            {
                empty($imgUrl[$i]) && $imgUrl[$i] = $this->load('qiniu')->uploadQiNiuImg('img_'.$i, md5(time().'bbsShowTimeImage_'.$i));
                empty($imgUrl[$i]) && $imgUrl[$i] = $oldShow[$i]['imgUrl'];
                $postInfo = $this->load('bbs')->getPostInfo($news_id[$i]);
                if(empty($postInfo) || $postInfo['is_show'] != 1 || empty($imgUrl[$i]))
                {
                    exit('序号为 '.$i.' 的图片信息不正确');
                }
                $dailyShow[] = array('imgUrl' => $imgUrl[$i], 'news_id' => $news_id[$i]);
            }
            $this->redis->set(REDIS_PREFIX.'DailyShow', json_encode($dailyShow));
            common::go('index.php?c=admin&a=showtime');
        }
    }
    /**
    *每日热答
    */
    public function dohotAns(){
        $boardId = 'hotans';
        $listNum = 15;
        $tagId = common::request('tagId', 'G',0);
        $tagList = $this->load('bbs')->getBoardTagList($boardId);
        $p = common::request('p', 'R', 1);
        $isSearch = common::request('isSearch', 'R', 0);
        $this->view->assign('tagId', $tagId);
        $this->view->assign('tagList', $tagList);
        $search = array('title' => '');
        //$search['title'] = common::request('title', 'R', '');
        $this->view->assign('search', $search);
        $rediskey=$basekey=REDIS_PREFIX.'hotAns_';

        //首页（只支持默认/热门/精华排序）
        if($force=common::request('force','G',0)){
            $posttype=common::request('order','R','new');
            switch ($posttype) {
                case 'hot':
                    $type="Hot";
                    $thisrediskey = $rediskey.$type;
                    $ids = $this->redis->ZREVRANGEBYSCORE($thisrediskey,'+inf',1);
                    break;
                case 'best':
                    $type="Best";
                    $thisrediskey = $rediskey.$type;
                    $ids = $this->redis->ZREVRANGEBYSCORE($thisrediskey,'+inf',1);
                    break;
                default :
                    $type="Top";
                    $thisrediskey = $rediskey.$type;
                    $ids = $this->redis->ZREVRANGEBYSCORE($thisrediskey,'+inf',time());
                    break;
            }

            $postList=array();
            foreach ($ids as $id){
                $sql="select news_id, uid, board,title,tag,real_addtime,lastupdate,is_show,loves,total_comment,is_top from r_news where news_id={$id}" ;
                //echo $sql;
                $postList[] = $this->db->getRow($sql);
            }
            $num=$this->redis->zcount($thisrediskey,'-inf','inf');
        }
        else
        {
            $order=common::request('order','R','');
            $query = ' where 1';
            $orderquery='';


            $parameter = '';//分页跳转的参数
            if ($isSearch)
            {
                $title = common::request('title', 'R', '');
                $parameter = '&'.urldecode(http_build_query($search, NULL, '&'));
                //!empty($search['title']) && $query .=  " and n.title like '%".$search['title']."%'";
                $search['title'] = $title;
            }




            $start = ($p-1) * $listNum;
            if($order=='comm'){
                $orderquery="total_comment DESC,";
                $order='';
            }
            if($order=='like'){
                $orderquery='loves DESC,';
                $order='';
            }
            //echo $order;
            if(isset($title) && $title != '')
            {
                $searcher = $this->load('xunSearch')->init('news');
                $num = $searcher->getCount("board:$boardId news_id:$title OR $title");
                $res = $searcher->search("board:$boardId news_id:$title OR $title",null,$listNum,$start);

                $news_id_in = [];
                foreach($res as $v){
                    $news_id_in[] = $v->news_id;
                }
                $news_id_in = "('".implode("','",$news_id_in)."')";
                $query = "WHERE n.news_id IN".$news_id_in;
                $start = 0;
                
                $postList = $this->db->getAll("select n.news_id, n.uid, n.board,n.title,n.tag,n.real_addtime,n.lastupdate,n.is_show,n.loves,n.total_comment,n.is_top from r_news as n ".$query." limit $start, $listNum");
                
                
            }elseif($order)
            {

                $ids='(';
                switch ($order) {
                    case 'hot':
                        # code...
                        $rediskey.='Hot';
                        if($tagId){
                            $rediskey.="_".$tagId;
                        }
                       // echo $rediskey;
                        $idsarr = $this->redis->ZREVRANGEBYSCORE($rediskey,'+inf',1);

                        break;
                    case 'best':
                        $rediskey.='Best';
                        if($tagId){
                            $rediskey.="_".$tagId;
                        }
                        $idsarr = $this->redis->ZREVRANGEBYSCORE($rediskey,'+inf',1);
                        //var_dump($idsarr);
                        break;
                    case 'top':
                        $rediskey.='Top';
                        if($tagId){
                            $rediskey.="_".$tagId;
                        }
                       // echo $rediskey;
                        $idsarr = $this->redis->ZREVRANGEBYSCORE($rediskey,'+inf',time());
                        break;
                    default:
                        # code...
                        //$idsarr=array();
                        break;
                }
                $num=count($idsarr);
                $ids.=implode(',',$idsarr);
                $ids.=')';

               // echo $ids;
                if($num)
                {
                    $query .= " and n.news_id in {$ids} ";
                    $query .= " and n.board like '%\"".$boardId."\"%'";
                     if($tagId > 0)
                    {
                        $query .= " and t.isOn = 1 and t.tagId= {$tagId}";
                        //echo $query;
                        $num = $this->db->getOne("select count(*) from r_tagPost as t left join r_news as n on n.news_id = t.news_id ".$query);
                        $sql="select n.news_id, n.uid, n.board,n.title,n.tag,n.real_addtime,n.lastupdate,n.is_show,n.loves,n.total_comment,n.is_top from r_tagPost as t left join r_news as n on n.news_id = t.news_id ".$query." order by n.real_addtime DESC limit $start, $listNum";
                        //echo $sql;
                        $postList = $this->db->getAll($sql);
                    }
                    else
                    {
                        $num = $this->db->getOne('select count(*) from r_news as n '.$query);
                        $postList = $this->db->getAll("select n.news_id, n.uid, n.board,n.title,n.tag,n.real_addtime,n.lastupdate,n.is_show,n.loves,n.total_comment,n.is_top from r_news as n ".$query." order by real_addtime DESC limit $start, $listNum");
                    }
                }
                else
                {
                    $postList = array();
                }
            }
            else
            {
                if($tagId > 0)
                {
                    $query .=" and n.board like '%\"".$boardId."\"%'";
                    $query .= " and t.isOn = 1 and t.tagId= {$tagId}";
                    $num = $this->db->getOne("select count(*) from r_tagPost as t left join r_news as n on n.news_id = t.news_id ".$query);
                    $postList = $this->db->getAll("select n.news_id, n.uid, n.board,n.title,n.tag,n.real_addtime,n.lastupdate,n.is_show,n.loves,n.total_comment,n.is_top from r_tagPost as t left join r_news as n on n.news_id = t.news_id ".$query." order by {$orderquery}n.real_addtime DESC limit $start, $listNum");
                }
                else
                {
                    $query .=" and n.board like '%\"".$boardId."\"%'";
                    $num = $this->db->getOne('select count(*) from r_news as n '.$query);
                    $sql="select n.news_id, n.uid, n.board,n.title,n.tag,n.real_addtime,n.lastupdate,n.is_show,n.loves,n.total_comment,n.is_top from r_news as n ".$query." order by {$orderquery}real_addtime DESC limit $start, $listNum";
                    $postList = $this->db->getAll($sql);
                }
            }
        }
        require FILE . 'lib/page.class.php';
        $page = new Page($num, $listNum);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);


        if($postList)
        {
            $time = $this->time;
            $redisKeyBase=REDIS_PREFIX.'gear_';
            foreach ($postList as & $v)
            {
                $v['header'] = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$v['uid'],'header');
                $v['nickname'] = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$v['uid'],'nickname');
                $v['lastComment'] = $this->db->getOne("select add_time from r_news_comment where news_id = '{$v['news_id']}' and is_show = 1 order by add_time DESC limit 1");
                $board = array();
                foreach (json_decode($v['board']) as $boardId) {
                    $boardInfo = $this->load('bbs')->getBoardInfo($boardId);
                    !empty($boardInfo) && $board[] = array('boardId' => $boardInfo['boardId'], 'boardName' => $boardInfo['boardName']);
                    unset($boardInfo);
                }
                $v['board'] = $board;
                $tag = array();
                if(common::is_json($v['tag']))
                {
                    foreach (json_decode($v['tag']) as $tagId) {
                        $tagInfo = $this->load('bbs')->getTagInfo($tagId);
                        !empty($tagInfo) && $tag[] = array('tagId' => $tagInfo['tagId'], 'tagName' => $tagInfo['tagName']);
                        unset($tagInfo);
                    }
                }
                else
                {
                    $tag[] = array('tagId' => 0, 'tagName' => $v['tag']);
                }
                $v['tag'] = $tag;
                $v['isHomeBest'] = $this->redis->ZSCORE($basekey.'Hot', $v['news_id']) >0 ? 1 : 0;
                $v['isBest'] = $this->redis->ZSCORE($basekey.'Best', $v['news_id'])>0 ? 1 : 0;
                $v['is_top'] = $this->redis->ZSCORE($basekey.'Top', $v['news_id']) > $time ? 1 : 0;

            }
        }


        $this->view->assign('search', $search);
        $this->view->assign('postList', $postList);
        $this->view->display('hotans');

    }
    /*
     * 社区-版块帖子列表
    */
    public function dopostList()
    {
        $boardId = common::request('boardId', 'G', '-1');
        $tagId = common::request('tagId', 'G',0);
        $sx = common::request('sx', 'G');
        $p = common::request('p', 'G', 1);
        $isSearch = common::request('isSearch', 'R', 0);
        $uid = common::request('uid','G',0);
        $query = ' where 1';
        $uid > 0 && $query .= " AND n.uid=$uid";
        $title = trim(common::request('title', 'R', ''));
        $search = compact('title','isSearch');
        $gid = common::request('gid',"G",0);
        $sTime = common::request('starttime', 'R');
        $eTime = common::request('endtime', 'R');
        $search['starttime'] = $sTime;
        $search['endtime'] = $eTime;

        $sxs = array(
            'all' => '全部',
            'show' => '显示',
            'unshow' => '不显示',
            /*'homehot' => '热门',
            'unhomehot' => '非热门',*/
            'best' => '精华',
            'unbest' => '非精华',
            'top' => '置顶',
            'untop' => '非置顶',
            'showtime' => 'showtime',
            'gspace' => '群空间'    
        );
        !isset($sxs[$sx]) && $sx = 'all';

        $this->view->assign('boardId', $boardId);

        $boardId == 'news' && $boardId = 0;

        $parameter = '';//分页跳转的参数
        if ($isSearch)
        {
            $parameter = '&'.http_build_query($search, NULL, '&');
            if(!empty($search['title'])){
                if(is_numeric($search['title'])){
                    $query .= " and n.news_id=".$search['title'];
                }else{
                    $query .=  " and n.title like '%".$search['title']."%' or n.content like '%".$search['title']."%'";
                }
            }
            !empty($search['starttime']) && $query .= ' and n.add_time>=' .strtotime($search['starttime']);
            !empty($search['endtime']) && $query .= ' and n.add_time<=' .strtotime($search['endtime']);
        }

        if($sx && $sx != 'all')
        {
            switch ($sx)
            {
                case 'show':
                    $query .= ' and is_show=1';
                    break;

                case 'unshow':
                    $query .= ' and is_show=0';
                    break;

                case 'homehot':
                    $query .= ' and is_home_hot=1';
                    break;

                case 'unhomehot':
                    $query .= ' and is_home_hot=0';
                    break;

                case 'best':
                    $query .= ' and is_best=1';
                    break;

                case 'unbest':
                    $query .= ' and is_best=0';
                    break;

                case 'top':
                    $query .= ' and is_top=1';
                    break;

                case 'untop':
                    $query .= ' and is_top=0';
                    break;
            }
        }

        $tagList = $this->load('bbs')->getBoardTagList($boardId);

        //var_dump($tagList);exit;
        $this->view->assign('tagId', $tagId);
        $this->view->assign('tagList', $tagList);
        $this->view->assign('search', $search);
        $listNum = 15;
        $start = ($p-1) * $listNum;
        
        $gid > 0 && $newsId = $this->db->getAll("select news_id from r_group_news where gid='$gid'");
        
        /*
        if(isset($title) && $title != ''){
            $searcher = $this->load('xunSearch')->init('news');
            $num = $searcher->getCount("news_id:$title OR $title");
            $title = str_replace('#','刱',$title);
            $res = $searcher->result("news_id:$title OR $title",null,$listNum,$start);
            
            $news_id_in = [];
            foreach($res as $v){
                $news_id_in[] = $v->news_id;
            }
            if(!empty($newsId)){
                foreach($newsId as $items){
                    $news_id_in[] = $items['news_id'];
                }
            }
            $news_id_in = "('".implode("','",$news_id_in)."')";
            $query = 'WHERE n.news_id IN'.$news_id_in;
            $start = 0;
            
            $postList = $this->db->getAll("select n.content,n.news_id, n.uid, n.board,n.title,n.tag,n.real_addtime,n.lastupdate,n.is_show,n.loves,n.total_comment,n.is_top,n.`source_client` from r_news as n ".$query." order by real_addtime DESC limit $start, $listNum");
        }else{
            $whereExt = '';
            $gid>0 && $whereExt = ' and n.news_id in("")';
            if(!empty($newsId)){
                foreach($newsId as $items){
                    $newsIds[] = $items['news_id'];
                }
                $ids = "('".implode("','",$newsIds)."')";
                $whereExt = " and n.news_id in $ids";

            }
            if($tagId > 0)
            {
                $query .= " and t.isOn = 1 and t.tagId= {$tagId} $whereExt";
                $num = $this->db->getOne("select count(*) from r_tagPost as t left join r_news as n on n.news_id = t.news_id ".$query);
                $postList = $this->db->getAll("select n.content,n.news_id, n.uid, n.board,n.title,n.tag,n.real_addtime,n.lastupdate,n.is_show,n.loves,n.total_comment,n.is_top,n.`source_client` from r_tagPost as t left join r_news as n on n.news_id = t.news_id ".$query." order by n.real_addtime DESC limit $start, $listNum");
            }
            else
            {
                $query .= $boardId == '-1' ? '' : " and n.board like '%\"".$boardId."\"%'";
                $query .= $whereExt;

                $num = $this->db->getOne('select count(*) from r_news as n '.$query);
                $postList = $this->db->getAll("select n.content,n.news_id, n.uid, n.board,n.title,n.tag,n.real_addtime,n.lastupdate,n.is_show,n.loves,n.total_comment,n.is_top,n.`source_client` from r_news as n ".$query." order by real_addtime DESC limit $start, $listNum");
            }
        }
        //因为xunsearch搜索精度不良，故改回mysql搜索
        */
        
        if(!empty($newsId)){
            foreach($newsId as $items){
                $news_id_in[] = $items['news_id'];
            }
            $news_id_in = "('".implode("','",$news_id_in)."')";
            $query = 'WHERE n.news_id IN'.$news_id_in;
        }
        if($tagId > 0)
        {
            $query .= " and t.isOn = 1 and t.tagId= {$tagId}";
            $nSql = $lSql = '';
            
            if ($sx == 'showtime') {
                $nSql = "select count(*) from r_tagPost as t inner join r_news as n on n.news_id = t.news_id " . $query . ' and t.news_id in (select news_id from r_tagPost where isOn=1 and tagId=' . $tagId . ' and news_id not in (select news_id from r_group_news)) and LOCATE("showtime", n.board)!=0';
                $lSql = "select n.content,n.news_id, n.uid, n.board,n.title,n.tag,n.real_addtime,n.lastupdate,n.is_show,n.loves,n.total_comment,n.is_top,n.`source_client` from r_tagPost as t inner join r_news as n on n.news_id = t.news_id ".$query.' and t.news_id  in (select news_id from r_tagPost where isOn=1 and tagId=' . $tagId . ' and news_id not in (select news_id from r_group_news)) and LOCATE("showtime", n.board)!=0 ' . "  order by n.real_addtime DESC limit $start, 25";
            } else if ($sx == 'gspace') {
                $nSql = "select count(*) from r_tagPost as t inner join r_news as n on n.news_id = t.news_id ".$query . ' and t.news_id in (select news_id from r_group_news) and LOCATE("showtime", n.board)=0';
                $lSql = "select n.content,n.news_id, n.uid, n.board,n.title,n.tag,n.real_addtime,n.lastupdate,n.is_show,n.loves,n.total_comment,n.is_top,n.`source_client` from r_tagPost as t inner join r_news as n on n.news_id = t.news_id ".$query. 'and t.news_id in (select news_id from r_group_news) and LOCATE("showtime", n.board)=0' . " order by n.real_addtime DESC limit $start, $listNum";
            } else {
                $nSql = "select count(*) from r_tagPost as t inner join r_news as n on n.news_id = t.news_id ".$query;
                $lSql = "select n.content,n.news_id, n.uid, n.board,n.title,n.tag,n.real_addtime,n.lastupdate,n.is_show,n.loves,n.total_comment,n.is_top,n.`source_client` from r_tagPost as t inner join r_news as n on n.news_id = t.news_id ".$query." order by n.real_addtime DESC limit $start, $listNum";
            }

            $num = $this->db->getOne($nSql);
            $postList = $this->db->getAll($lSql);
        }
        else
        {
            $query .= $boardId == '-1' ? '' : " and n.board like '%\"".$boardId."\"%'";
            $nSql = $lSql = '';
            
            if ($sx == 'showtime') {
                $nSql = 'select count(*) from r_news as n '.$query . ' and n.news_id in (select news_id from r_news ' . $query . '  and news_id not in (select news_id from r_group_news)) and LOCATE("showtime", n.board)!=0';
               $lSql = "select n.content,n.news_id, n.uid, n.board,n.title,n.tag,n.real_addtime,n.lastupdate,n.is_show,n.loves,n.total_comment,n.is_top,n.`source_client` from r_news as n ".$query. ' and n.news_id in (select news_id from r_news ' . $query . '  and news_id not in (select news_id from r_group_news)) and LOCATE("showtime", n.board)!=0 ' . " order by real_addtime DESC limit $start, $listNum";
            } else if ($sx == 'gspace') {
               $nSql = 'select count(*) from r_news as n '.$query . ' and n.news_id in (select news_id from r_group_news) and LOCATE("showtime", n.board)=0';
               $lSql = "select n.content,n.news_id, n.uid, n.board,n.title,n.tag,n.real_addtime,n.lastupdate,n.is_show,n.loves,n.total_comment,n.is_top,n.`source_client` from r_news as n ".$query." and n.news_id in (select news_id from r_group_news)  and LOCATE('showtime', n.board)=0 order by real_addtime DESC limit $start, $listNum";
            } else {
               $nSql = 'select count(*) from r_news as n '.$query;
               $lSql = "select n.content,n.news_id, n.uid, n.board,n.title,n.tag,n.real_addtime,n.lastupdate,n.is_show,n.loves,n.total_comment,n.is_top,n.`source_client` from r_news as n ".$query." order by real_addtime DESC limit $start, $listNum";
            }
            
            $num = $this->db->getOne($nSql);
            $postList = $this->db->getAll($lSql);
        }
        
        require FILE . 'lib/page.class.php';
        $page = new Page($num, $listNum,$parameter);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);


        if($postList)
        {
            $time = $this->time;
            $redisKey = $tagId > 0 ? REDIS_PREFIX.'TagPostList'.$tagId : REDIS_PREFIX.'BoardPostList'.$boardId;
            foreach ($postList as & $v)
            {
                $v['header'] = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$v['uid'],'header');
                $v['nickname'] = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$v['uid'],'nickname');
                $v['lastComment'] = $this->db->getOne("select add_time from r_news_comment where news_id = '{$v['news_id']}' and is_show = 1 order by add_time DESC limit 1");
                $v['real_addtime'] = date('Y-m-d H:i:s', $v['real_addtime']);
                $v['lastupdate'] = date('Y-m-d H:i:s', $v['lastupdate']);
                $v['lastComment'] = date('Y-m-d H:i:s', $v['lastComment']);
                $board = array();
                $arr = json_decode($v['board']);
                if(!empty($arr)){
                    foreach ( $arr as $boardId) {
                        $boardInfo = $this->load('bbs')->getBoardInfo($boardId);
                        !empty($boardInfo) && $board[] = array('boardId' => $boardInfo['boardId'], 'boardName' => $boardInfo['boardName']);
                        unset($boardInfo);
                    }
                }

                $v['board'] = $board;
                $tag = array();
                if(common::is_json($v['tag']))
                {
                    foreach (json_decode($v['tag']) as $tagId) {
                        $tagInfo = $this->load('bbs')->getTagInfo($tagId);
                        !empty($tagInfo) && $tag[] = array('tagId' => $tagInfo['tagId'], 'tagName' => $tagInfo['tagName']);
                        unset($tagInfo);
                    }
                }
                else
                {
                    $tag[] = array('tagId' => 0, 'tagName' => $v['tag']);
                }
                $v['tag'] = $tag;
                if($boardId != '') {
                    $v['is_top'] = $this->redis->ZSCORE($redisKey.'_New', $v['news_id']) > $time ? 1 : 0;
                }
                else {
                    $v['is_top'] = $this->redis->ZSCORE(REDIS_PREFIX.'NewsList', $v['news_id']) > $time ? 1 : 0;
                }
                $v['isHomeBest'] = $this->redis->zrevrank(REDIS_PREFIX.'TopHotpost', $v['news_id']) !== false ? 1 : 0;
                $v['isBest'] = $this->redis->ZSCORE($redisKey.'_Best', $v['news_id']) !== false ? 1 : 0;
                $v['isRecommend'] = $this->redis->zrevrank(REDIS_PREFIX.'BbsBestPost', $v['news_id']) !== false ? 1 : 0;
                $v['content'] = strip_tags($v['content']);
                $strlen = strlen($v['content']);
                if($strlen > 20){
                    $v['content'] = mb_substr($v['content'],0,20,'utf-8')."...";
                }
            }
        }
        $boardList = $this->load('bbs')->getBoardList(true);
        $boardList[] = array('boardId'=>'news','boardName' => '1.0资讯');
        $boardList[] = array('boardId'=>'-1','boardName' => '全部');
        $this->view->assign('uid', $uid);
        $this->view->assign('gid', $gid);
        $this->view->assign('postList', $postList);
        $this->view->assign('boardList', $boardList);
        $this->view->assign('sx', $sx);
        $this->view->assign('sxs', $sxs);
        $this->view->assign('p',$p);
        $this->view->display('postList');
    }
    /*
     * 社区-批处理帖子
    */
    public function dobatchPost()
    {
        require_once FILE.'../web/static/kindeditor/php/JSON.php';
        $json = new Services_JSON();

        $action = common::request('action', 'G');   // 操作类型 HomeHot/Best/cancelBest
        $postId = common::request('postId', 'G');   // 帖子id
        $postId = substr($postId, 0,-1);
        $message = '';
        $rel = array();

        if($action == '' || $postId == '') {
            $message = '参数不完整';
        }
        else {
            $postId = explode(',', $postId);
            foreach ($postId as $id) {
                $postInfo = $this->load('bbs')->getPostInfo($id);
                $postInfo['is_yd'] = strstr($this->redis->hget(REDIS_PREFIX.'NewsInfo_'.$id, 'board'),'"0"') !== false ? 1 : 0;
                $tmp = array('pid' => $id);
                switch ($action) {
                    case 'HomeHot':
                        $time = time() - 86400;
                        if($postInfo['is_show'] == 1)
                        {
                            $value = $this->db->getOne("select count(*) from r_news_comment where news_id ={$id} and is_show =1");
                             $tmp['suc'] = $this->redis->ZADD(REDIS_PREFIX.'TopHotpost', $value, $id) != false ? '成功' : '失败';
                             $this->db->updateRowTable('r_news', array('news_id' => $postInfo['news_id'],  'is_home_hot' => 1));
                        }
                        else{
                            $tmp['suc'] = '失败';
                        }
                        break;
                    case 'cancelHomeHot':
                        $tmp['suc'] = $this->redis->ZREM(REDIS_PREFIX.'TopHotpost', $id) != false ?'成功':'失败';
                        $this->db->updateRowTable('r_news', array('news_id' => $postInfo['news_id'],  'is_home_hot' => 0));
                        break;
                    case 'Best':
                        if($postInfo['is_show'] == 1)
                        {
                            foreach ($postInfo['board'] as $bid) {
                                $this->redis->ZADD(REDIS_PREFIX.'BoardPostList'.$bid['boardId'].'_Best', $postInfo['add_time'], $id);
                            }
                            foreach ($postInfo['tag'] as $tid) {
                                $this->redis->ZADD(REDIS_PREFIX.'TagPostList'.$tid['tagId'].'_Best', $postInfo['add_time'], $id);
                            }

                            // 更新装备关联
                            $this->db->query("update r_gear set updatetime='{$this->time}' where relate_id='{$id}'");
                            $this->db->updateRowTable('r_news', array('news_id' => $postInfo['news_id'],  'is_best' => 1));
                            $tmp['suc'] = '成功';
                        }
                        else{
                            $tmp['suc'] = '失败';
                        }
                        break;
                    case 'cancelBest':
                        foreach ($postInfo['board'] as $bid) {
                            $this->redis->ZREM(REDIS_PREFIX.'BoardPostList'.$bid['boardId'].'_Best', $id);
                        }
                        foreach ($postInfo['tag'] as $tid) {
                            $this->redis->ZREM(REDIS_PREFIX.'TagPostList'.$tid['tagId'].'_Best', $id);
                        }
                        $this->db->updateRowTable('r_news', array('news_id' => $postInfo['news_id'],  'is_best' => 0));
                        $tmp['suc'] = '成功';
                        break;
                    case 'Top':
                        if($postInfo['is_show'] == 1)
                        {
                            foreach ($postInfo['board'] as $bid) {
                                $this->redis->ZADD(REDIS_PREFIX.'BoardPostList'.$bid['boardId'].'_New', $postInfo['add_time']*10, $id);
                            }
                            foreach ($postInfo['tag'] as $tid) {
                                $this->redis->ZADD(REDIS_PREFIX.'TagPostList'.$tid['tagId'].'_New', $postInfo['add_time']*10, $id);
                            }
                            $postInfo['is_yd'] == 1 && $this->redis->ZADD(REDIS_PREFIX.'NewsList', $postInfo['add_time']*10, $id);

                            $this->db->updateRowTable('r_news', array('news_id' => $postInfo['news_id'],  'is_top' => 1));

                            $tmp['suc'] = '成功';
                        }
                        else{
                            $tmp['suc'] = '失败';
                        }
                        break;
                    case 'cancelTop':
                        foreach ($postInfo['board'] as $bid) {
                            $this->redis->ZREM(REDIS_PREFIX.'BoardPostList'.$bid['boardId'].'_New', $id);
                        }
                        foreach ($postInfo['tag'] as $tid) {
                            $this->redis->ZREM(REDIS_PREFIX.'TagPostList'.$tid['tagId'].'_New', $id);
                            $this->redis->ZREM(REDIS_PREFIX.'NewsList', $id);
                        }
                        $this->db->updateRowTable('r_news', array('news_id' => $postInfo['news_id'],  'is_top' => 0));
                        $tmp['suc'] = '成功';
                        break;
                    case 'Recommend':
                        if( $postInfo['is_show'] == 1 )
                        {
                            //时间热度映射表
                            $hotVal = array( 'hour12' => 50, 'hour24' => 30);
                            $score = $postInfo['total_comment'] + $postInfo['loves'];
                            $time = time() - $postInfo['add_time'];
                            if( $score > 5 )
                            {
                                if(  $time > 0 && $time <= 12*3600 )
                                {
                                    $score += $hotVal['hour12'];
                                }
                                elseif( $time > 12*3600 && $time <= 24*83600 )
                                {
                                    $score += $hotVal['hour24'];
                                }
                            }
                            $this->redis->ZADD( REDIS_PREFIX.'BbsBestPost', $score, $id );
                            $tmp['suc'] = '成功';
                        }
                        else{
                            $tmp['suc'] = '失败';
                        }
                        break;
                    case 'cancelRecommend':
                        $tmp['suc'] = $this->redis->ZREM( REDIS_PREFIX.'BbsBestPost', $id ) !== false ?'成功':'失败';
                        break;
                    default:
                        $tmp['suc'] = '无效操作'; // 参数无效
                        break;
                }
                $rel[] = $tmp;
                unset($tmp,$postInfo);
            }
        }
        echo $json->encode(array('message' => $message, 'rel' => $rel));
        exit;
    }
    /*
     * 社区-添加或查看帖子
    */
    public function dopostInfo()
    {
        $action = common::request('action', 'R', 'add');
        $postId = intval(common::request('postId', 'R', 0));
        $gid = intval(common::request('gid', 'R'));
        $channelList = common::$publishChannel;

        if($postId)
        {
            $gid = $this->db->getOne("select gid from r_group_news where news_id='{$postId}'");
        }

        $groupInfo = $gid ? $this->load('group')->getGroupInfo($gid) : [];

        if($action == 'add')
        {
            $postInfo = array('news_id'=> 0,
                            'uid' =>'',
                            'nickname' =>'',
                            'header' =>'',
                            'postId' =>0,
                            'board' => array(),
                            'title' =>'',
                            'thumb_img' =>array(),
                            'short_desc' => '',
                            'content' => '',
                            'tag' => array(),
                            'is_show' => 1,
                            'add_time' => time(),
                            'start_time' => 0,
                            'is_yd' => 0,
                            'otag' => '',
                            'a_channel' => '',
                            'a_start_time' => time(),
                            'a_end_time' => time(),
                            'gid'=>0
            );
            $boardList = $this->load('bbs')->getBoardList();
            foreach ($boardList as & $v) {
                unset($v['boardImg']);
                $v['isMem'] = 0;
            }
            $tagList = array();
        }
        else if($action == 'edit')
        {
            $postInfo = $this->load('bbs')->getPostInfo($postId, 1);

            if(common::request('type') == 'json')
            {
                exit(json_encode($postInfo ? $postInfo : []));
            }

            $postInfo['postId'] = $postInfo['news_id'];
            if(empty($postInfo))
            {
                exit('帖子不存在');
            }

            if($groupInfo)
            {
                $postInfo['is_top'] = $this->db->getOne("select is_top from r_group_news where news_id='{$postId}' and gid={$gid}");
            }

            $postInfo['gid']=$this->db->getOne("select gid from r_gear_ng where nid={$postId}");
            $boardList = $this->load('bbs')->getBoardList();
            foreach ($boardList as & $v) {
                unset($v['boardImg']);
                $v['isMem'] = in_array($v, $postInfo['board']) ? 1 : 0;
            }
            $postInfo['is_yd'] = $this->redis->hget(REDIS_PREFIX.'NewsInfo_'.$postId, 'board') == false ? 1 : (strstr($this->redis->hget(REDIS_PREFIX.'NewsInfo_'.$postId, 'board'),'"0"') !== false ? 1 : 0);
            $postInfo['otag'] = common::is_json($this->redis->hget(REDIS_PREFIX.'NewsInfo_'.$postId, 'tag')) ? $this->redis->hget(REDIS_PREFIX.'NewsInfo_'.$postId, 'otag'):$this->redis->hget(REDIS_PREFIX.'NewsInfo_'.$postId, 'tag');
            $tagList = array();
            foreach ($postInfo['board'] as $board) {
                $tagList = array_merge($tagList, $this->load('bbs')->getBoardTagList($board['boardId']));
            }
            foreach ($tagList as & $v) {
               unset($v['style'], $v['isHot']);
               $v['isMem'] = in_array($v, $postInfo['tag']) ? 1 : 0;
            }
        }
        else if($action == 'insert')
        {
            $title = common::request('title','P');
            $short_desc = common::request('short_desc','P');
            $uid = common::request('uid','P');
            $is_show = common::request('is_show','P');
            $start_time = common::request('start_time','P',0);
            $a_channel = common::request('a_channel','P','');
            $a_start_time = common::request('a_start_time','P',0);
            $a_end_time = common::request('a_end_time','P',0);
            $add_time = common::request('add_time','P',0);
            $content = common::request('content','P',0);
            $is_yd = common::request('is_yd','P',0);
            $otag = common::request('otag','P','');
            $boardId = common::request('boardId','P',0);
            $tagId = common::request('tagId','P',0);

            $boardId = $this->load('bbs')->checkBoard($boardId);
            $is_yd == 1 && $boardId[] = "0";
            $board = json_encode($groupInfo ? ['groupNews'] : $boardId);
            $tag = $this->load('bbs')->checkTag($tagId);
            $tagId = json_decode($tag, true);
            $start_time = strtotime($start_time);
            $a_start_time = strtotime($a_start_time);
            $a_end_time = strtotime($a_end_time);
            $add_time = strtotime($add_time);
            !$add_time && $add_time = time();
            $real_addtime = $lastupdate = time();
            $loves = $total_comment = 0;
            !$boardId && $boardId = [];

            //如果是添加装备并且没有添加togearid
            if(in_array('gearEval', $boardId)){
                if(!$togearid=common::request('togearid','R')){
                    exit('跑步装备评测必须填写装备id');
                }
                if(!$this->db->getOne("select count(1) from r_gear where gearId='{$togearid}'")){
                    exit('你选择的装备不存在');
                }
            }
              //小弄堂需求-去除
//            if(empty($title) || empty($content))
//            {
//                exit('参数不完整 ,<a id="return" href="?c=admin&a=postInfo">返回</a>');
//            }
            if(!empty($boardId) && in_array('hotans', $boardId)) {
                if(empty($title))
                {
                    exit('参数不完整 ,<a id="return" href="?c=admin&a=postInfo">返回</a>');
                }
            }
            if(empty($content))
            {
                exit('参数不完整 ,<a id="return" href="?c=admin&a=postInfo">返回</a>');
            }
            
            if($is_show && (($title && $this->load('badwords')->check($title)) || $this->load('badwords')->check($content))){
                exit('含有违禁词 ,<a id="return" href="?c=admin&a=postInfo">返回</a>');
            }

            if(!empty($a_channel))
            {
                if(!array_key_exists($a_channel, $channelList))
                {
                    exit('无法识别渠道类型，请检查后重试');
                }
                if(empty($a_start_time) || empty($a_end_time) || $a_start_time >= $a_end_time)
                {
                    exit('活动期限有误');
                }
                if($a_end_time <= time()){
                    $a_channel = '';
                    $a_start_time = $a_end_time = 0;
                }
            }
            else{
                $a_start_time = $a_end_time = 0;
            }

            extract($this->load('admin')->digPostImg($content)); // $content  $sourceImg  $thumb_img
            $imginfo = array();
            for($i=0;$i<count($sourceImg);$i++){
                $info = getimagesize($sourceImg[$i]);
                //if(!empty($info)){
                    $imginfo[$i]['width'] = isset($info[0]) ? $info[0] : 450;
                    $imginfo[$i]['height'] = isset($info[1]) ? $info[1] : 450;
                //}
            }
            $imginfo = json_encode($imginfo);
            $imgCount = count($thumb_img);
            $thumb_img = json_encode($thumb_img);
            $sourceImg = json_encode($sourceImg);
            $author = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$uid, 'author');
            $source_client = 1;
            $postInfo = compact('uid','title','short_desc','board','tag','sourceImg','is_show', 'start_time', 'author', 'content', 'tag', 'add_time','lastupdate','thumb_img','imgCount','a_channel','a_start_time','a_end_time','real_addtime','loves','total_comment','imginfo','source_client');
            $postId = $this->load('bbs')->insert($postInfo);

            if($postId)
            {
                if($groupInfo)
                {
                    $is_top = intval(common::request('is_top', 'P'));

                    $groupNews = [
                        'news_id' => $postId,
                        'uid' => $uid,
                        'is_show' => $is_show,
                        'is_top' => $is_top,
                        'addtime' => $add_time,
                        'gid' => $gid, 
                    ];

                    $this->db->insertRow('r_group_news', $groupNews, 2);
                    !$is_top && $this->redis->zadd(REDIS_PREFIX.'GroupNews_'.$gid, $add_time, $postId);
                }

                // 关联『装备快讯、评测』
                if(in_array('gearEval', $boardId) || in_array('gearNews', $boardId))
                {
                    if(!$this->db->getOne("select count(1) from r_gear where relate_id='{$postId}'"))
                    {
                        if($imgCount > 0)
                        {
                            $gearImages = $thumb_img;
                        }
                        else
                        {
                            $gearImages = json_encode(array('http://' . $this->config['host'] . '/static/images/default.png'));
                        }

                        if(in_array('gearEval', $boardId))
                        {
                            $gearImages = $this->db->getOne("select images from r_gear where gearId='{$togearid}'");
                        }

                        $gearInfo = array(
                            'catId' => 1,
                            'type' => in_array('gearEval', $boardId) ? 2 : 3,
                            'name' => $title ? $title : $content,
                            'relate_id' => $postId,
                            'shortDesc' => strip_tags($content),
                            'relate_content' => json_encode(array(
                                'uid' => $uid,
                            )),
                            'images' => $gearImages,
                            'addTime' => $add_time,
                            'isShow' => $is_show,
                        );

                        $this->db->insertRow('r_gear', $gearInfo);

                        if(!empty($togearid))
                        {
                            $this->db->query("delete from r_gear_ng where nid='{$postId}'");
                            $this->db->insertRow('r_gear_ng', array('nid' => $postId,'gid' => $togearid), 1);
                        }
                    }
                }

                $postInfo['otag'] = $otag;
                $postInfo['news_id'] = $postId;

                $postInfoTmp = array();

                foreach ($postInfo as $pk => $pv)
                {
                    !$pv && !is_numeric($pv) && $pv = '';

                    $postInfoTmp[$pk] = $pv;
                }

                $this->redis->hmset(REDIS_PREFIX .'NewsInfo_'.$postId, $postInfoTmp);

                foreach ($boardId as $v) {
                    if(!empty($v))
                    {
                        $this->db->insertRowTable('r_boardPost', array('boardId' => $v,'news_id' => $postId,'isOn' => 1));
                    }
                }
                foreach ($tagId as $v) {
                    $this->db->insertRowTable('r_tagPost', array('tagId' => $v, 'news_id' => $postId,'isOn' => 1));
                }
                if($is_show == 0 && $start_time >= time())
                {
                    $this->redis->sadd(REDIS_PREFIX . 'NewsShowTimers', $postId);
                }
                elseif($is_show != 0)
                {
                    if(!empty($a_channel))
                    {
                        if($is_yd == 1)
                        {
                            $this->redis->HSET(REDIS_PREFIX.'ActivityNews', $a_channel, $postId);
                        }
                        foreach ($boardId as $v) {
                            if(!empty($v))
                            {
                                $this->redis->ZADD(REDIS_PREFIX.'ACT_'.$a_channel.'_'.$v, $a_start_time, $postId);
                            }
                        }
                        foreach ($tagId as $v) {
                            $this->redis->ZADD(REDIS_PREFIX.'ACT_'.$a_channel.'_'.$v, $a_start_time, $postId);
                        }
                    }
                    else{
                        $is_yd == 1 && $this->redis->ZADD(REDIS_PREFIX . 'NewsList', $add_time, $postId);
                        foreach ($boardId as $v) {
                            if(!empty($v))
                            {
                                $this->redis->zadd(REDIS_PREFIX.'BoardPostList'.$v.'_New', $add_time, $postId);
                                $this->redis->zadd(REDIS_PREFIX.'BoardPostList'.$v.'_Hot', 0, $postId);
                                
                                if($v=='showtime'){
                                    //24小时内排序
                                    $author_gender = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$uid, 'gender');
                                    if($author_gender == 1){
                                        $score = $add_time;
                                    }elseif($author_gender == 2){
                                        $score = $add_time+20000000000;
                                    }else{
                                        $score = $add_time+10000000000;
                                    }
                                    //清除旧数据
                                    //$this->redis->ZREMRANGEBYSCORE(REDIS_PREFIX.'BoardPostList'.$boardId.'_New24H',$add_time-48*3600,$add_time-24*3600);
                                    //$this->redis->ZREMRANGEBYSCORE(REDIS_PREFIX.'BoardPostList'.$boardId.'_New24H',$add_time-48*3600+10000000000,$add_time-24*3600+10000000000);
                                    //$this->redis->ZREMRANGEBYSCORE(REDIS_PREFIX.'BoardPostList'.$boardId.'_New24H',$add_time-48*3600+20000000000,$add_time-24*3600+20000000000);
                                    
                                    //$this->redis->zadd(REDIS_PREFIX.'BoardPostList'.$v.'_New24H',$score,$news_id);
                                }
                            }
                        }
                        foreach ($tagId as $v) {
                            $this->redis->zadd(REDIS_PREFIX.'TagPostList'.$v.'_New', $add_time, $postId);
                            $this->redis->zadd(REDIS_PREFIX.'TagPostList'.$v.'_Hot', 0, $postId);
                        }
                    }
                }
                //过滤话题
                $this->load('topic')->filterPost($postInfo);
                common::go("index.php?c=admin&a=postInfo&action=edit&postId={$postId}\n");
            }
            exit('操作失败');
        }
        else if($action == 'update')
        {
            $oldPost = $this->load('bbs')->getPostInfo($postId);

            $title = common::request('title','P');
            $short_desc = common::request('short_desc','P');
            $is_show = intval(common::request('is_show','P'));
            $start_time = common::request('start_time','P',0);
            $a_channel = common::request('a_channel','P','');
            $uid = common::request('uid','P');
            $a_start_time = common::request('a_start_time','P',0);
            $a_end_time = common::request('a_end_time','P',0);
            $add_time = common::request('add_time','P',0);
            $content = common::request('content','P',0);
            $is_yd = common::request('is_yd','P',0);
            $otag = common::request('otag','P','');
            $boardId = common::request('boardId','P',0);
            $tagId = common::request('tagId','P',0);
            $boardId = $this->load('bbs')->checkBoard($boardId);
            $is_yd == 1 && $boardId[] = "0";
            $tag = $this->load('bbs')->checkTag($tagId);
            $tagId = json_decode($tag, true);
            $start_time = strtotime($start_time);
            $a_start_time = strtotime($a_start_time);
            $a_end_time = strtotime($a_end_time);
            $add_time = strtotime($add_time);
            $lastupdate = time();

            !$boardId && $boardId = [];
            $board = json_encode($groupInfo ? ['groupNews'] : $boardId);

            if(in_array('gearEval', $boardId)){
                if(!$togearid=common::request('togearid','R')){
                    exit('跑步装备评测必须填写装备id');
                }
                if(!$this->db->getOne("select * from r_gear where gearId='{$togearid}' limit 1")){
                    exit('你选择的装备不存在');
                }
            }

            if(!empty($boardId) && in_array('hotans', $boardId))
            {
                    if(empty($title) || empty($postId))
                    {
                        exit('参数不完整');
                    }
            }
            else
            {
                if(empty($content) || empty($postId))
                {
                    exit('参数不完整');
                }
                if($is_show && ($title && ($this->load('badwords')->check($title)) || $this->load('badwords')->check($content))){
                    exit('含有违禁词 ,<a id="return" href="?c=admin&a=postInfo">返回</a>');
                }
            }

            // 从定时显示任务列表中删除
            $this->redis->SREM(REDIS_PREFIX. 'NewsShowTimers', $postId);
            if(!empty($a_channel))
            {
                if(!array_key_exists($a_channel, $channelList))
                {
                    exit('无法识别渠道类型，请检查后重试');
                }
                if(empty($a_start_time) || empty($a_end_time) || $a_start_time >= $a_end_time)
                {
                    exit('活动期限有误');
                }
                if($a_end_time <= time()){
                    $a_channel = '';
                    $a_start_time = $a_end_time = 0;
                }
            }
            else{
                $a_start_time = $a_end_time = 0;
            }
            $news_id = $postId;
            // 如果是 非图文混排帖， 不修改内容及图片
            if($oldPost['type'] == 0)
            {
                $content = $oldPost['content'];
                $sourceImg = $oldPost['sourceImg'];
                $thumb_img = $oldPost['thumb_img'];
            }
            else
            {
                extract($this->load('admin')->digPostImg($content)); // $content  $sourceImg  $thumb_img
            }
            $imginfo = array();
            for($i=0;$i<count($sourceImg);$i++){
                $info = getimagesize($sourceImg[$i]);
                //if(!empty($info)){
                    $imginfo[$i]['width'] = isset($info[0]) ? $info[0] : 450;
                    $imginfo[$i]['height'] = isset($info[1]) ? $info[1] : 450;
                //}
            }
            $imginfo = json_encode($imginfo);
            $imgCount = count($thumb_img);
            $thumb_img = json_encode($thumb_img);
            $sourceImg = json_encode($sourceImg);
            $author = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$uid, 'author');
            $postInfo = compact('news_id','uid','title','short_desc','board','tag','author','sourceImg','is_show', 'start_time', 'content', 'tag', 'add_time','lastupdate','thumb_img','imgCount','a_channel','a_start_time','a_end_time','imginfo');

            if(!$add_time)
            {
                unset($postInfo['add_time']);
            }

            if($this->load('bbs')->update($postInfo))
            {
                if($groupInfo)
                {
                    $is_top = intval(common::request('is_top', 'P'));

                    $groupNews = [
                        'news_id' => $news_id,
                        'uid' => $uid,
                        'is_show' => $is_show,
                        'is_top' => $is_top,
                        'gid' => $gid, 
                    ];

                    $this->db->insertRow('r_group_news', $groupNews, 2);
                    $groupNews = $this->db->getRow("select * from r_group_news where news_id='{$news_id}' and gid='{$gid}'");

                    if($groupNews)
                    {
                        $add_time = $groupNews['addtime'];
                        
                        if($is_top)
                        {
                            $this->redis->zrem(REDIS_PREFIX.'GroupNews_'.$gid, $news_id);
                        }
                        else
                        {
                            $this->redis->zadd(REDIS_PREFIX.'GroupNews_'.$gid, $add_time, $news_id);
                        }

                    }
                }

                // 关联『装备快讯、评测』
                if(in_array('gearEval', $boardId) || in_array('gearNews', $boardId))
                {
                    if($imgCount > 0)
                    {
                        $gearImages = $thumb_img;
                    }
                    else
                    {
                        $gearImages = json_encode(array('http://' . $this->config['host'] . '/static/images/default.png'));
                    }

                    if(in_array('gearEval', $boardId))
                    {
                        $gearImages = $this->db->getOne("select images from r_gear where gearId='{$togearid}'");
                    }

                    $gearInfo = array(
                        'catId' => 1,
                        'type' => in_array('gearEval', $boardId) ? 2 : 3,
                        'name' => $title ? $title : $content,
                        'relate_id' => $postId,
                        'shortDesc' => strip_tags($content),
                        'relate_content' => json_encode(array(
                            'uid' => $uid,
                        )),
                        'images' => $gearImages,
                        'addTime' => $add_time,
                        'isShow' => $is_show,
                    );

                    if(!$this->db->getOne("select count(1) from r_gear where relate_id='{$postId}'"))
                    {
                        $this->db->insertRow('r_gear', $gearInfo);
                    }
                    else
                    {
                        $sqlStr = common::arrayToString($gearInfo);
                        $this->db->query("update r_gear set {$sqlStr} where relate_id='{$postId}'");
                    }

                    if(!empty($togearid))
                    {
                        $this->db->query("delete from r_gear_ng where nid='{$postId}'");
                        $this->db->insertRow('r_gear_ng', array('nid' => $postId,'gid' => $togearid), 1);
                    }
                }

                $postInfo['otag'] = $otag;
                $this->redis->hmset(REDIS_PREFIX .'NewsInfo_'.$postId, $postInfo);
                $this->redis->zrem(REDIS_PREFIX . 'NewsList', $postId);
                // 如果该有帖子是运营的活动文章，则从运营文章中删除该运营类型
                empty($oldPost['a_channel']) && $this->redis->hdel(REDIS_PREFIX.'ActivityNews', $oldPost['a_channel']);
                foreach ($oldPost['board'] as $v) {
                    if(!empty($v['boardId']))
                    {
                        $this->db->updateRowTable('r_boardPost', array('boardId' => $v['boardId'],'news_id' => $postId,'isOn' => $is_show));
                        foreach (common::$postListType as $type) {
                            $this->redis->zrem(REDIS_PREFIX.'BoardPostList'.$v['boardId'].'_'.$type, $postId);
                        }
                        // 如果该有帖子是运营的活动文章
                        empty($oldPost['a_channel']) && $this->redis->SREM(REDIS_PREFIX.'ACT_'.$oldPost['a_channel'].'_'.$v['boardId'], $postId);
                        
                        //24小时内文章
                        if($v['boardId'] == 'showtime'){
                            $this->redis->zrem(REDIS_PREFIX.'BoardPostList'.$v['boardId'].'_New24H',$news_id);
                        }
                    }
                }
                foreach ($oldPost['tag'] as $v) {
                    $this->db->updateRowTable('r_tagPost', array('tagId' => $v['tagId'], 'news_id' => $postId,'isOn' => $is_show));
                    foreach (common::$postListType as $type) {
                        $this->redis->zrem(REDIS_PREFIX.'TagPostList'.$v['tagId'].'_'.$type, $postId);
                    }
                    // 如果该有帖子是运营的活动文章
                    !empty($oldPost['a_channel']) && isset($v['boardId']) && $this->redis->SREM(REDIS_PREFIX.'ACT_'.$oldPost['a_channel'].'_'.$v['boardId'], $postId);
                }
                $this->db->query("update r_group_news set is_show = $is_show where news_id = $postId");//更新活动帖子
                if($is_show != 1)
                {
                    if($start_time >= time())
                    {
                        $this->redis->sadd(REDIS_PREFIX . 'NewsShowTimers', $postId);
                    }
                    //隐藏帖子
                    foreach ($boardId as $v) {
                        if(!empty($v))
                        {
                            $this->db->updateRowTable('r_boardPost', array('boardId' => $v,'news_id' => $postId,'isOn' => 0));
                            $this->redis->zrem(REDIS_PREFIX.'BoardPostList'.$v.'_New', $postId);
                            $this->redis->zrem(REDIS_PREFIX.'BoardPostList'.$v.'_Hot', $postId);
                            
                            if($v=='showtime'){
                                //24小时内排序
                                $this->redis->zrem(REDIS_PREFIX.'BoardPostList'.$v.'_New24H',$news_id);
                            }
                        }
                    }
                    foreach ($tagId as $v) {
                        $this->db->updateRowTable('r_tagPost', array('tagId' => $v, 'news_id' => $postId,'isOn' => 0));
                        $this->redis->zrem(REDIS_PREFIX.'TagPostList'.$v.'_New', $postId);
                        $this->redis->zrem(REDIS_PREFIX.'TagPostList'.$v.'_Hot', $postId);
                    }
                }
                else
                {
                    if(!empty($a_channel))
                    {
                        if($is_yd == 1)
                        {
                            $this->redis->HSET(REDIS_PREFIX.'ActivityNews', $a_channel, $postId);
                        }
                        foreach ($boardId as $v) {
                            if(!empty($v))
                            {
                                $this->redis->ZADD(REDIS_PREFIX.'ACT_'.$a_channel.'_'.$v, $a_start_time, $postId);
                            }
                        }
                        foreach ($tagId as $v) {
                            $this->redis->ZADD(REDIS_PREFIX.'ACT_'.$a_channel.'_'.$v, $a_start_time, $postId);
                        }
                    }
                    else
                    {
                        $lastCT = $this->db->getOne("select add_time from r_news_comment where news_id = '{$news_id}' and is_show = 1 order by comment_id DESC limit 1");
                        $lastCT = intval($lastCT);
                        $is_yd == 1 && $this->redis->ZADD(REDIS_PREFIX . 'NewsList', $add_time, $postId);
                        foreach ($boardId as $v) {
                            if(!empty($v))
                            {
                                $this->db->updateRowTable('r_boardPost', array('boardId' => $v,'news_id' => $postId,'isOn' => 1));
                                $this->redis->zadd(REDIS_PREFIX.'BoardPostList'.$v.'_New', $add_time, $postId);
                                $this->redis->zadd(REDIS_PREFIX.'BoardPostList'.$v.'_Hot', $lastCT, $postId);
                                
                                if($v=='showtime'){
                                    //24小时内排序
                                    $author_gender = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$uid, 'gender');
                                    if($author_gender == 1){
                                        $score = $add_time;
                                    }elseif($author_gender == 2){
                                        $score = $add_time+20000000000;
                                    }else{
                                        $score = $add_time+10000000000;
                                    }
                                    //清除旧数据
                                    //$this->redis->ZREMRANGEBYSCORE(REDIS_PREFIX.'BoardPostList'.$boardId.'_New24H',$add_time-48*3600,$add_time-24*3600);
                                    //$this->redis->ZREMRANGEBYSCORE(REDIS_PREFIX.'BoardPostList'.$boardId.'_New24H',$add_time-48*3600+10000000000,$add_time-24*3600+10000000000);
                                    //$this->redis->ZREMRANGEBYSCORE(REDIS_PREFIX.'BoardPostList'.$boardId.'_New24H',$add_time-48*3600+20000000000,$add_time-24*3600+20000000000);
                                    
                                    //$this->redis->zadd(REDIS_PREFIX.'BoardPostList'.$v.'_New24H',$score,$news_id);
                                }
                            }
                        }
                        foreach ($tagId as $v) {
                            $this->db->updateRowTable('r_tagPost', array('tagId' => $v, 'news_id' => $postId,'isOn' => 1));
                            $this->redis->zadd(REDIS_PREFIX.'TagPostList'.$v.'_New', $add_time, $postId);
                            $this->redis->zadd(REDIS_PREFIX.'TagPostList'.$v.'_Hot', $lastCT, $postId);
                        }
                    }
                    $this->load('topic')->filterPost($postInfo);
                }
                exit( '编辑成功');
            }
            exit( '操作失败');
        }

        $this->view->assign('groupInfo', $groupInfo);
        $this->view->assign('gid', $gid);
        $this->view->assign('action', $action);
        $this->view->assign('postInfo', $postInfo);
        $this->view->assign('channelList', common::$publishChannel);
        $this->view->assign('boardList', $boardList);
        $this->view->assign('tagList', $tagList);
        $this->view->display('postInfo');
    }

    /*
     * 删除帖子(软删除)
     */
    public function dodelPost($countParams){
        $news_id = common::request('newsid', 'G');
        if(!empty($news_id))
        {
            //删除帖子
            $this->db->update("update r_news set is_show = 0 where news_id = {$news_id}");
        }
        $this->dopostList();
    }
    
    /*
    * 帖子添加版块时展示版块下标签
    */
    public function doaddPostBoard()
    {
        require_once FILE.'../web/static/kindeditor/php/JSON.php';
        $json = new Services_JSON();

        $boardId = common::request('boardId', 'G');
        $boardId = trim($boardId);
        $message = '';
        $tagList = array();
        if($boardId)
        {
            $tagList = $this->load('bbs')->getBoardTagList($boardId);
            foreach ($tagList as &$v) {
                unset($v['style'], $v['isHot']);
            }
        }
        else
        {
            $message = '没事不要乱点哈';
        }

        if(empty($tagList)) $message = '该版块下标签为空';
        echo $json->encode(array('message' => $message, 'tagList' => $tagList));
        exit;
    }

    /**
     * 装备合辑
     */
    public function dogearSets()
    {
        $ac = common::request('ac');
        $gid = common::request('gid', 'G');
        $page = common::request('p');
        $possess = common::request('top');
        $gid = intval($gid);
        $page = intval($page);
        $page < 1 && $page = 1;
        $possess = intval($possess);

        $this->load('gear');
        $gearSetInfo = $gid ? $_ENV['gear']->getGearSetInfoByGid($gid) : array();

        if(in_array($ac, array('update', 'top')) && $gid && !$gearSetInfo)
        {
            exit('这个装备已回到火星，现在小编同学要轮到你了，开始传送：3、2、1、0，欢迎你来到火星，『火星电信5G最好用！』祝您旅途愉快！');
        }

        if($ac == 'update')
        {
            $msg = NULL;

            !$gearSetInfo && $gearSetInfo = array('name' => '', 'shortDesc' => '', 'relate_content' => '', 'images' => '', 'likes' => '', 'possess' => 0);

            if(common::method() == 'POST')
            {
                $setInfo = common::multiRequest(array_keys($gearSetInfo), 'P');

                foreach($setInfo as $key => $value)
                {
                    $gearSetInfo[$key] = $value;
                }

                if($gearSetInfo['name'] && $gearSetInfo['relate_content'])
                {
                    $gearSetInfo['type'] = 1;
                    $gearSetInfo['isShow'] = 1;
                    $gearSetInfo['likes'] = intval($gearSetInfo['likes']);
                    $gearSetInfo['possess'] = intval($gearSetInfo['possess']);
                    $gearSetInfo['images'] = $images = $this->load('qiniu')->uploadQiNiuImg('images', md5(microtime(TRUE)));
                    !$gearSetInfo['images'] && $gearSetInfo['images'] = 'http://' . $this->config['host'] . '/static/images/default.png';
                    $gearSetInfo['images'] = json_encode(array($gearSetInfo['images']));

                    if(!$gid)
                    {
                        $gearSetInfo['addTime'] = $this->time;
                    }
                    else
                    {
                        $gearSetInfo['gearId'] = $gid;
                        unset($gearSetInfo['addTime']);

                        if(!$images)
                        {
                            unset($gearSetInfo['images']);
                        }
                    }

                    unset($gearSetInfo['img']);

                    $status = $_ENV['gear']->updateGearSetInfoByGid($gearSetInfo);
                    $msg = $status ? '更新成功' : '发生了一个问题';

                    $gearSetInfo = $_ENV['gear']->getGearSetInfoByGid($status ? $status : $gid);
                }
                else
                {
                    $msg = '参数不完整';
                }
            }

            $this->view->assign('msg', $msg);
            $this->view->assign('gearSetInfo', $gearSetInfo);
            $this->view->display('admin_gear_sets_update');
        }
        elseif($ac == 'possess' && $gearSetInfo)
        {
            // 置顶，possess代为置顶

            $status = $_ENV['gear']->setGearSetTop($gid, $possess) ? 1 : 0;
            common::go(common::reurl());
        }
        elseif($ac == 'getSetInfo' && $gid)
        {
            // 获取指定装备内容

            !$gearSetInfo && $gearSetInfo = array();
             echo json_encode($gearSetInfo);
        }
        elseif($ac == 'del' && $gid)
        {
            // 删除

            $_ENV['gear']->setGearSetHide($gid);
            common::go(common::reurl());
        }
        else
        {
            // 列表

            $gearSets = $_ENV['gear']->getGearListByType('gearSet', 'new', $page, 100);

            $this->view->assign('gearSets', $gearSets);
            $this->view->display('admin_gear_sets');
        }
    }

    /*
     * 装备列表
    */
    public function dogearList()
    {
        $s = common::request('s','R','');
        $p = common::request('p', 'R', 1);

        $query = ' where type=0 ';
        $search = array('name' => '',
                        'brand' => '',
                        'gender'  => '',
                        'cat' => '',
                        'shoeCat' => '',
                        'footType' => '',
                        'funcTag' => '',
                        'footCircle' => '',
                        'nullDesc' => -1,
                        'isShow' => -1,
                        'shopUrl' => -1
                        );

        common::request('s', 'P') && $p =1;

        $parameter = ''; //分页跳转的参数
        if ($s == "search")
        {
            $name = common::request('name', 'R', '');
            $brand = common::request('brand', 'R', 0);
            $gender = common::request('gender','R','');
            $shoeCat = common::request('shoeCat','R','');
            $footType = common::request('footType','R','');
            $funcTag = common::request('funcTag','R','');
            $footCircle = common::request('footCircle','R','');
            $nullDesc = common::request('nullDesc','R');
            $isShow = common::request('isShow','R',0);
            $shopUrl = common::request('shopUrl','R');
            $cat = common::request('cat','R','');

            $search = compact('name', 'brand', 'cat', 'gender','shoeCat','footType', 'funcTag','footCircle', 'nullDesc', 'isShow','shopUrl');

            $parameter = compact('s','name', 'brand', 'cat', 'gender','shoeCat','footType', 'funcTag','footCircle', 'nullDesc', 'isShow','shopUrl');
            $parameter = '&'.urldecode(http_build_query($parameter, NULL, '&'));

            $query .= empty($brand) ? "":" and g.brand = '{$brand}'";
            $query .= empty($cat) ? "":" and g.catId = '{$cat}'";
            $query .= empty($gender) ? "" : " and g.gender = '{$gender}' ";
            $query .= empty($shoeCat) ? "" : " and g.shoeCat = '{$shoeCat}' ";
            $query .= empty($footType) ? "" : " and g.footType like '%{$shoeCat}%' ";
            $query .= empty($footCircle) ? "" : " and g.footCircle like '%{$footCircle}%' ";
            $query .= empty($funcTag) ? "" : " and g.funcTag = '{$funcTag}' ";
            $query .= $nullDesc == -1 ? "" : ($nullDesc ? " and g.shortDesc = '' " : " and g.shortDesc != ''");
            $query .= $isShow == -1 ? "" : " and g.isShow = '{$isShow}' ";
            $query .= $shopUrl == -1 ? "":($shopUrl ? " and g.shopUrl != '' ":" and g.shopUrl = '' ");
        }

        //分页
        require FILE . 'lib/page.class.php';
        // $listNum = 20;
        $listNum = 200;
        $start = ($p - 1) * $listNum;
        
        if(isset($name) && $name != ''){
            //$searcher = $this->load('xunSearch')->init('gear');
            //$num = $searcher->getCount("isShow:1 name:$name");
            //$res = $searcher->search("gearId:$name OR $name", 'gearId', $listNum, $p);
            if(is_numeric($name)){
                $query = ' WHERE g.gearId = '.$name;
            }else{
                $query = ' WHERE g.name like "%'.$name.'%"';
            }
            $start = 0;
        }

        $num = $this->db->getOne('select count(*) from r_gear AS g LEFT JOIN r_gear_brand AS b ON b.brandId = g.brand'. $query);

        $page = new Page($num, $listNum, $parameter);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);
        
        $gearList = $this->db->getAll('select g.gearId from r_gear AS g '. $query. " order by g.gearId DESC limit $start,$listNum");

        $shoeAttr = common::$shoeAttr;

        $brandList = $this->db->getAll("select * from r_gear_brand where isShow = 1 order by sorder ASC");
        $catList = $this->db->getAll("select * from r_gear_cat where isShow = 1 order by sorder ASC");

        if($gearList)
        {
            foreach ($gearList as & $v) {
                $v = $this->load('gear')->getGearInfo($v['gearId']);
                $v['comscore'] = $this->load('gear')->gearComScore($v['gearId']);
                $redisKeyBase=REDIS_PREFIX.'gear_';
                $v['hot']=$this->redis->zscore($redisKeyBase.'hot','g:'.$v['gearId']) ? : 0;
                $v['best']=$this->redis->zscore($redisKeyBase.'best','g:'.$v['gearId']) ? :0;
                $v['cat'] = array();
                foreach ($catList as & $c) {
                    if($c['catId']==$v['catId']){
                        $v['cat'] = $c;
                        break;
                    }

                }
            }
        }

        $categorysList = $this->db->getAll("select catId as value,catName as name from r_gear_cat where isShow = 1 order by sorder ASC");
        foreach ($categorysList as & $v) {
            $sql = "select brandId as value,brandName as name from r_gear_brand where catId={$v['value']} order by sorder ASC";
            $v['sub'] = $this->db->getAll($sql);
        }

        $this->view->assign('brandList',$brandList);
        $this->view->assign('catList', $catList);
        $this->view->assign('search', $search);
        $this->view->assign('gearList', $gearList);
        $this->view->assign('shoeAttr', $shoeAttr);
        $this->view->assign('rootCatJson', json_encode($categorysList));
        $this->view->display('gearList');
    }
    /*
     * 装备详情
    */
    public function dogearInfo()
    {
        $type = common::request('type', 'G');
        if($type == 'add')
        {
            $gearInfo = array('gearId'  => 0,
                              'name'    => '',
                              'catId'    => '',
                              'brand'   => array('brandId' => 0, 'brandName' => ''),
                              'shortDesc'   => '',
                              'gender'      => 0,
                              'shoeCat'     => 0,
                              'footType'    => array(),
                              'footCircle'  => array(),
                              'feature'    => 0,
                              'funcTag'    => 0,
                              'level'    => 0,
                              'weight'    => 0,
                              'price'    => 0,
                              'minprice'    => 0,
                              'currency'    => 0,
                              'publishTime' => time(),
                              'isShow'    => 1,
                              'evaluate'    => array(),
                              'shopUrl'  => '',
                              'images'  => array(),
                              'lighty'  => 0,
                              'shocklessen'  => 0,
                              'comfort'  => 0,
                              'fiexibility'  => 0,
                              'griplity'  => 0,
                              'durablility'  => 0,
                              'sizefeel'  => 0,
                              'score'  => 0,
                              'blendent'  => array(),
                              'goods_id' => '',
                            );
            $action = 'insert';
            $shihuoId = common::request('shihuoId');            
            if(!empty($shihuoId)){
                  $shihuo =  $this->db->getRow("select * from r_gear_shihuo where goods_id = ${shihuoId}");
                  $gearInfo['name'] = $shihuo['title'];
                  $gearInfo['shortDesc'] = $shihuo['content'];
                  $gearInfo['price'] = $shihuo['price'];
                  $gearInfo['goods_id'] = $shihuo['goods_id'];
                  $gearInfo['images'] = json_decode($shihuo['pics'], true);
                  $gearInfo['images'] = array_slice($gearInfo['images'], 0, 5);
                  if($shihuo['root_cat_name']=='鞋类'){
                      $gearInfo['catId'] = 1;
                      $sql = "select brandId from r_gear_brand where shihuoName='{$shihuo['root_brand_name']}' and catId=1 and isShow=1 limit 1";
                      $gearInfo['brand']['brandId'] = $this->db->getOne($sql);
                  }
            }
        }
        else
        {
            $gearId = common::request('gearId', 'G');
            $gearInfo = $this->load('gear')->getGearInfo($gearId, false, true);
            $gearInfo && $gearInfo['shortDesc'] = str_replace("<br>", "\r\n", $gearInfo['shortDesc']);
            $action = 'update';

            if($type == 'json')
            {
                exit(json_encode($gearInfo));
            }
        }

        $eleLength = array('imgLength' => count($gearInfo['images']), 'evaluate' => count($gearInfo['evaluate']), 'blendent' => count($gearInfo['blendent']));

        $shoeAttr = common::$shoeAttr;
        $fTSelected = array(); // 足型复选
        $fCSelected = array(); // 适合足类复选
        if(empty($gearInfo['footType'])){
            $gearInfo['footType'] = array();
        }
        if(empty($gearInfo['footCircle'])){
            $gearInfo['footCircle'] = array();
        }
        foreach ($shoeAttr['footType'] as $key => $value) {
            $fTSelected[$key] = in_array($key, $gearInfo['footType']) ? 1 : 0;
        }
        foreach ($shoeAttr['footCircle'] as $key => $value) {
            $fCSelected[$key] = in_array($key, $gearInfo['footCircle']) ? 1 : 0;
        }

        $categorysList = $this->db->getAll("select catId as value,catName as name from r_gear_cat where isShow = 1 order by sorder ASC");
        foreach ($categorysList as & $v) {
            $sql = "select brandId as value,brandName as name from r_gear_brand where catId={$v['value']} and isShow = 1 order by sorder ASC";
            $v['sub'] = $this->db->getAll($sql);
        }

        $this->view->assign('action', $action);
        $this->view->assign('gearInfo', $gearInfo);
        $this->view->assign('eleLength', $eleLength);
        $this->view->assign('shoeAttr', $shoeAttr);
        $this->view->assign('fTSelected', $fTSelected);
        $this->view->assign('fCSelected', $fCSelected);
        $this->view->assign('rootCatJson',json_encode($categorysList));
        $this->view->assign('staticHost', $this->config['img-host']);
        $this->view->display('gearInfo');
    }
    /*
     * 装备添加或信息修改
    */
    public function dogearAction()
    {
        $action = common::request('action', 'P');
        $name = common::request('name', 'P');
        $catId = common::request('catId', 'P');
        $brand = common::request('brand', 'P');
        $shortDesc = common::request('shortDesc', 'P');
        $gender = common::request('gender', 'P');
        $shoeCat = common::request('shoeCat', 'P');
        $footType = common::request('footType', 'P');
        $footCircle = common::request('footCircle', 'P');
        $feature = common::request('feature', 'P');
        $weight = common::request('weight', 'P');
        $price = common::request('price', 'P');
        $minprice = common::request('minprice', 'P');
        $currency = common::request('currency', 'P');
        $publishTime = common::request('publishTime', 'P');
        $isShow = common::request('isShow', 'P');

        $maxImage = common::request('maxImage', 'P',0);  // 装备图片最大数量
        $maxBlendent = common::request('maxBlendent', 'P',0); // 装备配色最大数量

        $funcTag = common::request('funcTag', 'P');
        $level = common::request('level', 'P');
        $shopUrl = common::request('shopUrl', 'P','');
        $imgUrl = common::request('imgUrl', 'P','');
        $evaluate = common::request('evaluate', 'P'); // 评测

        $score = common::request('score', 'P', 0);
        $lighty = common::request('lighty', 'P', 0);
        $shocklessen = common::request('shocklessen', 'P', 0);
        $comfort = common::request('comfort', 'P', 0);
        $fiexibility = common::request('fiexibility', 'P', 0);
        $griplity = common::request('griplity', 'P', 0);
        $durablility = common::request('durablility', 'P', 0);
        $sizefeel = common::request('sizefeel', 'P', 0);
        $goods_id = common::request('goods_id','P',''); //识货商品id



        if(!$action || !$name || !$catId)
        {
            exit('参数不完整');
        }
        $catId = intval($catId);
        $brand = intval($brand);
        $gender = intval($gender);
        $shoeCat = intval($shoeCat);
        $footType = json_encode($footType);
        $footCircle = json_encode($footCircle);
        $feature = intval($feature);
        $price = round($price,2);
        $currency = intval($currency);
        $publishTime = strtotime($publishTime);
        $maxImage = intval($maxImage);
        $maxBlendent = intval($maxBlendent);

        $name = trim($name);
        $name = str_replace('"', '', $name);
        $name = addslashes($name);
        $shortDesc = str_replace("\r\n", "<br>", $shortDesc);
        $shortDesc = trim($shortDesc);
        $images = '[]';
        $funcTag = intval($funcTag);
        $level = intval($level);

        $time = time();
        $cnyPrice = $currency == 1 ? round($price * 6.21, 2) : $price;

        $this->load('qiniu');
        $this->load('bbs');
        $evaluate = is_array($evaluate) ? implode('|', $evaluate) : '';
        // 验证测评参数的合法性
        if(is_array($evaluate) && !emtpy($evaluate))
        {
            foreach ($evaluate as $k => $v)
            {
                $v = intval($v);
                if($v < 1)
                {
                    unset($evaluate[$k]);
                }
                if(!$_ENV['bbs']->getPostInfo($v))
                {
                    unset($evaluate[$k]);
                }
                $evaluate = array_values($evaluate);
            }
        }
        if($maxImage > 0)  // 装备图片
        {
            $images = array();
            for($i=0; $i<$maxImage; $i++)
            {
                $imgName = md5($time.common::getHashStr().$i);
                $gearImg = $_ENV['qiniu']->uploadQiNiuImg('picture_'.$i, $imgName);
                if($gearImg)
                {
                    $images[] = $gearImg;
                }
                else if(isset($imgUrl[$i]))
                {
                    if(strrpos($imgUrl[$i],'shihuo.hupucdn.com')){
                        $images[] = $imgUrl[$i];
                    }else{
                        $images[] = $_ENV['qiniu']->saveNetImg($imgUrl[$i], $imgName);
                    }
                }
            }
            $images = json_encode($images);
        }
        if($maxBlendent > 0)  // 装备配色
        {
            $blendent = array();
            $oBlenImgs = common::request('blenImg', 'P');
            for($i=0; $i<$maxBlendent; $i++)
            {
                $color = common::request('color_'.$i, 'P');

                if(empty($color))
                {
                    continue;
                }
                // 将配色色值转换为字符串
                $color = implode('|', $color);

                $imgName = md5($time.common::getHashStr().$i);
                $blenImg = $_ENV['qiniu']->uploadQiNiuImg('picture_'.$i, $imgName);
                if($blenImg)
                {
                    $img = $blenImg;
                }
                else if(isset($oBlenImgs[$i]))
                {
                    $img = $oBlenImgs[$i];
                }

                if(isset($img))
                {
                    $blendent[] = compact('color', 'img');
                    unset($img);
                }
            }
        }

        $gearInfo = compact('name','catId','brand','shortDesc','shortDesc','gender','shoeCat','footType','footCircle','feature','weight','price','minprice','currency','cnyPrice','publishTime','funcTag','level','images','shopUrl','evaluate','isShow','lighty','shocklessen','comfort','fiexibility','griplity','durablility','sizefeel','score','goods_id');

        if(empty($goods_id)){
           unset($gearInfo['goods_id']);
        }

        if($action == 'insert')
        {
            $gearInfo['addTime'] = $gearInfo['updatetime'] = $time;
            $gearId = $this->load('gear')->insert($gearInfo);
            if($gearId)
            {
                $gearInfo['gearId'] = $gearId;
                // redis 写入
                $this->redis->hmset(REDIS_PREFIX.'GearInfo_'.$gearId, $gearInfo);
                if($isShow == 1)
                {
                    $this->redis->ZADD(REDIS_PREFIX.'GearsBy_pri', $cnyPrice, $gearId);
                    $this->redis->ZADD(REDIS_PREFIX.'GearsBy_lik', 0, $gearId);
                    $this->redis->ZADD(REDIS_PREFIX.'GearsBy_pub', $publishTime, $gearId);
                    $this->redis->ZADD(REDIS_PREFIX.'BrandGList_'.$brand, $publishTime, $gearId);
                }

                // //初始化3个redis，最新，最热，精华
                $redisKeyBase=REDIS_PREFIX.'gear_';
                $this->redis->zadd($redisKeyBase.'new',$gearInfo['addTime'],'g:'.$gearId);
                //装备初始化有10的热度和精华
                $this->redis->zadd($redisKeyBase.'hot',20,'g:'.$gearId);
                $this->redis->zadd($redisKeyBase.'best',20,'g:'.$gearId);

                $this->redis->zadd($redisKeyBase.'new',$gearInfo['addTime'],'g:'.$gearId);
                $this->redis->zadd($redisKeyBase.'hot',20,'g:'.$gearId);
                $this->redis->zadd($redisKeyBase.'best',20,'g:'.$gearId);
            }
            else
            {
                exit('添加失败');
            }
        }
        else
        {
            $gearId = common::request('gearId', 'P');

            $oldInfo = $this->load('gear')->getGearInfo($gearId, false);
            $gearInfo['gearId'] = $gearId;
            $gearInfo['updatetime'] = $time;
            if($this->load('gear')->update($gearInfo))
            {
                $this->redis->hmset(REDIS_PREFIX.'GearInfo_'.$gearId, $gearInfo);
                //   列表s
                if($isShow == 1)
                {
                    if($oldInfo['isShow'] != 1)
                    {
                        $likes = intval($oldInfo['likes']);
                        $publishTime += $likes;
                        $this->redis->ZADD(REDIS_PREFIX.'GearsBy_pri', $cnyPrice, $gearId);  // 价格排行
                        $this->redis->ZADD(REDIS_PREFIX.'GearsBy_lik', $likes, $gearId); // 喜欢数排行
                        $this->redis->ZADD(REDIS_PREFIX.'GearsBy_pub', $publishTime, $gearId);  // 上市时间排行
                        $this->redis->ZADD(REDIS_PREFIX.'BrandGList_'.$brand, $publishTime, $gearId);  // 品牌装备列表
                    }
                }
                else
                {
                    $this->redis->ZREM(REDIS_PREFIX.'GearsBy_pri', $gearId);
                    $this->redis->ZREM(REDIS_PREFIX.'GearsBy_lik', $gearId);
                    $this->redis->ZREM(REDIS_PREFIX.'GearsBy_pub',$gearId);
                    $this->redis->ZREM(REDIS_PREFIX.'BrandGList_'.$brand,$gearId);
                }
            }
            else
            {
                exit('编辑失败');
            }
        }
        if(!empty($blendent))
        {
            $blenData = array('addtime' => $this->time, 'is_delete' => 0);
            $this->load('admin');
            foreach ($blendent as $v)
            {
                $_ENV['admin']->addGearBlendent($gearId, array_merge($blenData, $v));
            }
        }
        echo '<a href="index.php?c=admin&a=gearInfo&type=edit&gearId='.$gearId.'">操作成功 ------- 查看</a>';
        exit;
    }
    /*
    * 获取帖子信息
    */
    public function dogetPostInfo()
    {
        require_once FILE.'../web/static/kindeditor/php/JSON.php';
        $json = new Services_JSON();

        $postId = common::request('id', 'G');
        $postId = intval($postId);
        $message = '';
        $data = array();
        if($postId)
        {
            $info = $this->load('bbs')->getPostInfo($postId);
            if(!empty($info))
            {
                $data['t'] = $info['title'];
                $data['img'] = array_slice($info['thumb_img'], 0, 3);
            }
            else
            {
                $message = '非法的帖子id';
            }
        }
        else
        {
            $message = '帖子id不能为空';
        }

        echo $json->encode(array('message' => $message, 'data' => $data));
        exit;
    }
    /*
    * 删除配色
    */
    public function dodelBlendent()
    {
        require_once FILE.'../web/static/kindeditor/php/JSON.php';
        $json = new Services_JSON();

        $id = common::request('id', 'G'); // 配色id
        $gearId = common::request('gearId', 'G'); // 装备id
        $id = intval($id);
        $gearId = intval($gearId);

        $message = ''; // 错误信息
        $rel = FALSE;
        if($id && $gearId)
        {
            if($this->load('admin')->delBlendent($gearId, $id) === FALSE)
            {
                $message = '失败';
            }
            else
            {
                $rel = TRUE;
            }
        }
        else
        {
            $message = '非法的参数';
        }

        echo $json->encode(array('message' => $message, 'rel' => $rel));
        exit;
    }

    /*
     * 装备品牌列表
    */
    public function dobrandList()
    {
        $brandList = $this->db->getAll('select * from r_gear_brand order by sorder ASC');

        $this->view->assign('brandList', $brandList);
        $this->view->display('brandList');
    }
    /*
     * 装备品牌编辑添加
    */
    public function dobrandInfo()
    {
        $type = common::request('type', 'G');
        if($type == 'add')
        {
            $brandInfo = array('brandId' => 0, 'brandName' => '', 'catId' => 0, 'logo' => '', 'sorder' => '', 'shihuoName'=>'', 'isShow' => 1);
            $action = 'insert';
        }
        else
        {
            $brandId = common::request('brandId', 'G');
            $brandInfo = $this->db->getRow("select * from r_gear_brand where brandId=$brandId");
            $action = 'update';
        }
        $this->view->assign('categorys', $this->db->getAll('select * from r_gear_cat where isShow=1 order by sorder ASC'));
        $this->view->assign('action', $action);
        $this->view->assign('brandInfo', $brandInfo);
        $this->view->display('brandInfo');
    }
    /*
     * 装备品牌添加或信息修改
    */
    public function dobrandAction()
    {
        $action = common::request('action', 'P');
        $brandName = common::request('brandName', 'P');
        $logo = common::request('logo', 'P');
        $isShow = common::request('isShow', 'P');
        $sorder = common::request('sorder', 'P');
        $catId = common::request('catId', 'P');

        if(!$action || !$brandName || !$catId)
        {
            exit('参数不完整');
        }
        $newLogo = $this->load('qiniu')->uploadQiNiuImg('newLogo', md5(time().common::getHashStr(6)));
        $newLogo && $logo = $newLogo;
        $isShow = intval($isShow);
        $isShow != 0 && $isShow =1;
        $brandInfo = compact('brandName','catId','logo','sorder','isShow');
        if($action == 'insert')
        {
            if($this->db->getOne("select brandId from r_gear_brand where brandName = '{$brandName}' and catId={$catId} "))
            {
                exit('品牌名称重复');
            }
            $brandId = $this->load('gear')->insertBrand($brandInfo);
            if($brandId)
            {
                $brandInfo['brandId'] = $brandId;
                $this->redis->hmset(REDIS_PREFIX.'BrandInfo_'.$brandId, $brandInfo);
                $isShow && $this->redis->ZADD(REDIS_PREFIX.'BrandList', $sorder, $brandId);
            }
            else
            {
                exit('添加失败');
            }
        }
        else
        {
            $brandId = common::request('brandId', 'P');
            if($this->db->getOne("select brandId from r_gear_brand where brandName = '{$brandName}' and catId={$catId} and brandId != '{$brandId}'"))
            {
                exit('装备名称重复');
            }
            $brandInfo['brandId'] = $brandId;
            if(!$this->load('gear')->updateBrand($brandInfo))
            {
                exit('编辑失败');
            }
            $this->redis->hmset(REDIS_PREFIX.'BrandInfo_'.$brandId, $brandInfo);
            if($isShow == 1)
            {
                $this->redis->ZADD(REDIS_PREFIX.'BrandList', $sorder, $brandId);
            }
            else
            {
                $this->redis->ZREM(REDIS_PREFIX.'BrandList', $brandId);
            }
        }
        echo '<a href="index.php?c=admin&a=brandInfo&type=edit&brandId='.$brandId.'">操作成功 ------- 查看</a>';
        exit;
    }

      /*
     * 装备品类列表
    */
    public function docatList()
    {
        $catList = $this->db->getAll('select * from r_gear_cat order by sorder ASC');

        $this->view->assign('catList', $catList);
        $this->view->display('catList');
    }
    /*
     * 装备品类编辑添加
    */
    public function docatInfo()
    {
        $type = common::request('type', 'G');
        if($type == 'add')
        {
            $catInfo = array('catId' => 0, 'catName' => '', 'logo' => '', 'sorder' => '', 'isShow' => 1);
            $action = 'insert';
        }
        else
        {
            $catId = common::request('catId', 'G');
            $catInfo = $this->db->getRow("select * from r_gear_cat where catId = '{$catId}'");
            $action = 'update';
        }
        $this->view->assign('action', $action);
        $this->view->assign('catInfo', $catInfo);
        $this->view->display('catInfo');
    }
    /*
     * 装备品类添加或信息修改
    */
    public function docatAction()
    {
        $action = common::request('action', 'P');
        $catName = common::request('catName', 'P');
        $logo = common::request('logo', 'P');
        $isShow = common::request('isShow', 'P');
        $sorder = common::request('sorder', 'P');

        if(!$action || !$catName)
        {
            exit('参数不完整');
        }
        $newLogo = $this->load('qiniu')->uploadQiNiuImg('newLogo', md5(time().common::getHashStr(6)));
        $newLogo && $logo = $newLogo;
        $isShow = intval($isShow);
        $isShow != 0 && $isShow =1;
        $catInfo = compact('catName','logo','sorder','isShow');
        if($action == 'insert')
        {
            if($this->db->getOne("select catId from r_gear_cat where catName = '{$catName}'"))
            {
                exit('品类名称重复');
            }
            $catId = $this->db->insertRowTable('r_gear_cat', $catInfo);
            
        }
        else
        {
            $catId = common::request('catId', 'P');
            if($this->db->getOne("select catId from r_gear_cat where catName = '{$catName}' and catId != '{$catId}'"))
            {
                exit('品类名称重复');
            }
            $catInfo['catId'] = $catId;
            if(!$this->db->updateRowTable('r_gear_cat', $catInfo))
            {
                exit('编辑失败');
            }
             
        }
        echo '<a href="index.php?c=admin&a=catInfo&type=edit&catId='.$catId.'">操作成功 ------- 查看</a>';
        exit;
    }


    /*
     * 识货列表
    */
    public function doshihuoList()
    {
        $s = common::request('s','R','');
        $p = common::request('p', 'R', 1);

        $query = ' where 1=1 ';
        $order = ' order by a.update_time DESC';
        $search = array('name' => '',
                        'rootCat' => '',
                        'childCat' => '',
                        'filter1'  => '',
                        'filter2'  => '',
                        );

        common::request('s', 'P') && $p =1;

        $parameter = ''; //分页跳转的参数
        if ($s == "search")
        {
            $name = common::request('name', 'R', '');
            $rootCat = common::request('rootCat', 'R', '');
            $childCat = common::request('childCat', 'R', '');
            $filter1 = common::request('filter1','R','');
            $filter2 = common::request('filter2','R','');


            $search = compact('name', 'rootCat', 'childCat', 'filter1','filter2');

            $parameter = compact('s','name', 'rootCat','childCat', 'filter1','filter2');
            $parameter = '&'.urldecode(http_build_query($parameter, NULL, '&'));

            $query .= empty($name) ? "":" and ( a.goods_id={$name} or b.gearId={$name} )";
            $query .= empty($rootCat) ? "":" and a.root_cat_name = '{$rootCat}'";
            $query .= empty($childCat) ? "":" and a.child_cat_name = '{$childCat}'";

            if($filter1=="1"){
                $query .= " AND (b.gearId is NULL or a.goods_id is NULL) ";
            }else if($filter1=="2"){
                $query .=  " AND (b.gearId is NOT NULL and a.goods_id is NOT NULL) 
                AND a.goods_id in ( select distinct goods_id from r_gear_channel where merchant='淘宝' AND status=1) ";
            }

            if($filter2=="1"){
                $query .=   " AND a.supplier_count>0 AND a.goods_id in ( select distinct goods_id from r_gear_channel where merchant='淘宝' AND status=1) ";
            }else if($filter2=="2"){
                $query .=  " AND a.supplier_count=0 ";
            }else if($filter2=="3"){
                $order =  " order by diff asc ";
                $query .= " AND a.price-prev_price<0 AND a.price>0 AND a.goods_id in ( select distinct goods_id from r_gear_channel where merchant='淘宝' AND status=1) ";
            }else if($filter2=="4"){
                $query .=  " AND a.update_time <= DATE_ADD(now(),INTERVAL -1 DAY) ";
            }

        }

        //分页
        require FILE . 'lib/page.class.php';
        $listNum = 30;
        $start = ($p - 1) * $listNum;

        $filterList1  = array(
            '1' => '未关联的装备',
            '2' => '已关联的装备'
            );

        $filterList2  = array(
            '1' => '有渠道的商品',
            '2' => '没有渠道的商品',
            '3' => '降价商品',
            '4' => '过期的商品',
            );
        
        $num = $this->db->getOne('select count(*) from  r_gear_shihuo  a left join r_gear b on a.goods_id = b.goods_id '. $query);
        $page = new Page($num, $listNum, $parameter);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);
        
        $shihuoList = $this->db->getAll('select a.goods_id,a.pic,a.title,a.root_cat_name,a.child_cat_name,a.supplier_count,b.gearId,b.name,a.price,a.price-prev_price as diff,b.images 
             from r_gear_shihuo  a left join r_gear b on a.goods_id = b.goods_id 
              '. $query. $order ." limit $start,$listNum");


        $rootCatList = $this->db->getAll("select distinct root_cat_name as name from r_gear_shihuo");
        foreach ($rootCatList as & $v) {
            $sql = "select distinct child_cat_name as name from r_gear_shihuo where root_cat_name='".$v['name']."'";
            $v['sub'] = $this->db->getAll($sql);
        }

        foreach ($shihuoList as & $v) {
            if(!empty($v['images'])){
                $v['images'] = json_decode($v['images']);
                $v['pic'] = current($v['images']);
            }
        }
        $this->view->assign('rootCatJson',json_encode($rootCatList));
        $this->view->assign('shihuoList',$shihuoList);
        $this->view->assign('filterList1',$filterList1);
        $this->view->assign('filterList2',$filterList2);
        $this->view->assign('search', $search);
        $this->view->display('shihuoList');
    }


    /*
     * 识货列表
    */
    public function doshihuoGrouponList()
    {
        $s = common::request('s','R','');
        $p = common::request('p', 'R', 1);

        $query = ' where a.finish_time>now() and 1=1 ';
        $order = ' order by a.start_time DESC';
        $search = array('name' => '',
                        'rootCat' => '',
                        'filter1'  => '',
                        );

        common::request('s', 'P') && $p =1;

        $parameter = ''; //分页跳转的参数
        if ($s == "search")
        {
            $name = common::request('name', 'R', '');
            $rootCat = common::request('rootCat', 'R', '');
            $filter1 = common::request('filter1','R','');


            $search = compact('name', 'rootCat', 'filter1');

            $parameter = compact('s','name', 'rootCat', 'filter1');
            $parameter = '&'.urldecode(http_build_query($parameter, NULL, '&'));

            $query .= empty($name) ? "":" and ( a.title like '%{$name}%' ) ";
            $query .= empty($rootCat) ? "":" and a.cat_name = '{$rootCat}'";

            if($filter1=="1"){
                $query .= " AND (b.id is NULL ) ";
            }else if($filter1=="2"){
                $query .=  " AND (b.id is NOT NULL) ";
            }

        }

        //分页
        require FILE . 'lib/page.class.php';
        $listNum = 30;
        $start = ($p - 1) * $listNum;

        $filterList1  = array(
            '1' => '未关联的装备',
            '2' => '已关联的装备'
            );

        
        $num = $this->db->getOne('select count(*) from  r_gear_shihuogroupon  a left join r_flash_sales b on a.groupon_id = b.shihuo_grouponid '. $query);
        $page = new Page($num, $listNum, $parameter);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);
        
        $shihuoList = $this->db->getAll('select a.groupon_id,a.title,a.start_time,a.finish_time,a.img_path,a.original_price,a.price,b.id as flashId  from r_gear_shihuogroupon a left join r_flash_sales b on a.groupon_id = b.shihuo_grouponid  
              '. $query. $order ." limit $start,$listNum");


        foreach ($shihuoList as & $v) {
            if(strtotime($v['finish_time']) > time()){
                $v['status'] = '<font color=green>进行中</font>';
            }else if(strtotime($v['finish_time']) < time()){
                $v['status'] = '<font color=red>已结束</font>';
            }else{
                $v['status'] = '';
            }
        }


        $rootCatList = $this->db->getAll("select distinct cat_name as name from r_gear_shihuogroupon");
         
        $this->view->assign('rootCatJson',json_encode($rootCatList));
        $this->view->assign('shihuoList',$shihuoList);
        $this->view->assign('filterList1',$filterList1);
        $this->view->assign('search', $search);
        $this->view->display('shihuoGrouponList');
    }

    /*
     * 装备热门搜索词
    */
    public function dogearHotKw()
    {
        $keywords = $this->redis->ZREVRANGEBYSCORE(REDIS_PREFIX.'GearKw', '+inf', '-inf', array('WITHSCORES' => 1,'limit' => array(0, 10)));
        if(!empty($keywords))
        {
            foreach ($keywords as & $v) {
                $v = base64_decode($v);
            }
            $keywords = implode($keywords, '|');
        }
        else
        {
            $keywords = '';
        }
        $this->view->assign('keywords', $keywords);
        $this->view->display('gearKeywords');
    }
    /*
     * 设置装备热门搜索词
    */
    public function dosetGearHotKw()
    {
        $keywords = common::request('keywords', 'P');
        $keywords = str_ireplace('｜', '|', $keywords);
        if(empty($keywords))
        {
            exit('请输入要设置的热门搜索词');
        }
        $redisKey =  REDIS_PREFIX.'GearKw';
        $this->redis->del($redisKey);
        $keywords = explode('|', $keywords);
        foreach ($keywords as $key => $words) {
            $words = trim($words);
            $words = base64_encode($words);
            $words && $this->redis->ZADD($redisKey, 100-$key, $words);
        }
        $url ='index.php?c=admin&a=gearHotKw';
        echo '<a href="'.$url.'">设置完成，查看关键词</a>';
        exit;
    }

    /**
    * 每日好价
    */
    public function dogearHomeBestGoods(){
        $ids = $this->redis->lrange(REDIS_PREFIX.'GearHomeBestGoods',0,-1);
        $list = array();
        if(!empty($ids))
        {
            foreach ($ids as & $v) {
                $gear =  $this->db->getRow("select * from r_gear where gearId = {$v}");
                $gear['images'] = current(json_decode($gear['images']));
                $list[] =  $gear;
            }
        }
        
        $this->view->assign('list', $list);
        $this->view->display('gearHomeBestGoods');
    }
    /**
    * 设置每日好价
    */
    public function dosetGearHomeBestGoods(){
        $action  =  common::request('action');
        $gearId  =  common::request('gearId','');

        $gear = $this->db->getRow("select gearId from r_gear where gearId = {$gearId}");
        if(!empty($gear)){
            if($action=='add'){
                $this->redis->lpush(REDIS_PREFIX.'GearHomeBestGoods',$gearId);
            } else if($action=='del'){
                $this->redis->lrem(REDIS_PREFIX.'GearHomeBestGoods',$gearId,1);
            }
        }
        $url ='index.php?c=admin&a=gearHomeBestGoods';
        echo '<a href="'.$url.'">设置完成，查看</a>';
    }
    /*
     * 装备主页推荐
    */
    public function dogearHomeBest()
    {
        $todayBest = $this->load('gear')->homeRecGear();
        for($i = 0; $i<=3; $i++)
        {
            if(!isset($todayBest[$i]))
            {
                $todayBest[$i] = array('title' => array('color' => '#22DD22','content' => 'test'),
                                       'describe' => '描述',
                                       'img' => '',
                                       'url' => '',
                    );
            }
        }
        $this->view->assign('staticHost', $this->config['img-host']);
        $this->view->assign('list', $todayBest);
        $this->view->display('gearHomeBest');
    }
    /*
     * 设置装备主页推荐
    */
    public function dosetGearHmBest()
    {
        $data = array();
        $content = common::request('content', 'P');
        $color = common::request('color', 'P');
        $describe = common::request('describe', 'P');
        $img = common::request('img', 'P');
        $url = common::request('url', 'P');
        $sorder = common::request('sorder', 'P');
        foreach ($content as $key => $value) {
            if($value)
            {
                $imgNew = $this->load('qiniu')->uploadQiNiuImg('imgNew_'.$sorder[$key]);
                $data[] = array('title' => array('color' => $color[$key],'content' => $value),
                                       'describe' => $describe[$key],
                                       'img' => $imgNew ? $imgNew : $img[$key],
                                       'url' => $url[$key],
                    );
            }
        }
        $this->redis->set(REDIS_PREFIX.'GearHomeBest', json_encode($data));
        $url ='index.php?c=admin&a=gearHomeBest';
        echo '<a href="'.$url.'">设置完成，查看结果</a>';
        exit;
    }
    /*
     * 推荐装备列表
    */
    public function dogearSetList()
    {
        $p = common::request('p', 'G', 1);
        $offset = 20;

        $num = $this->db->getone('select count(*) from r_gear_set order by tid DESC');

        //分页
        require FILE . 'lib/page.class.php';
        $page = new Page($num, $offset);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);

        $start = ($p - 1) * $offset;
        $sql = "select * from r_gear_set order by tid DESC limit $start,$offset";
        $setList = $this->db->getall($sql);
        if($setList)
        {
            foreach ($setList as & $v) {
                $gearList = @json_decode($v['gears'], true);
                if(is_array($gearList))
                {
                    $v['gears'] = substr(implode(',', $gearList), 0,30).'...';
                }
                $v['url'] = 'joggers://gearList/'.$v['tid'];
            }
        }

        $this->view->assign('setList', $setList);
        $this->view->display('gearSetList');
    }
    /*
     * 装备集合详情
    */
    public function dogearSetInfo()
    {
        $type = common::request('type', 'G', 'add');
        if($type == 'add')
        {
            $info = array('tid' => 0,
                          'name' => '',
                          'gears'   => '',
                          'url' =>''
                        );
        }
        else
        {
            $tid = common::request("tid", 'G');
            $info = $this->db->getRow("select * from r_gear_set where tid = '{$tid}'");
            if(!$info)
            {
                exit("无相关记录");
            }
            $info['gears'] = implode(@json_decode($info['gears'], true),'*');
            $info['url'] = 'joggers://gearList/'.$tid;
        }

        $this->view->assign("action", $type == 'add' ? 'insert' : 'update');
        $this->view->assign("info", $info);
        $this->view->display("gearSetInfo");
    }
    /*
     * 装备集合编辑、添加
    */
    public function dogearSetAction()
    {
        $action = common::request('action', 'P');
        $name = common::request('name', 'P');
        $gears = common::request('gears', 'P');

        $list = explode('*', $gears);
        $gears = array();
        if($list)
        {
            foreach ($list as $v) {
                $v = trim($v);
                $gearInfo = $this->load('gear')->getGearInfo($v);
                if($gearInfo && $gearInfo['isShow'] == 1 && !in_array($v, $gears))
                {
                    $gears[] = $v;
                }
            }
        }
        if(empty($gears))
            exit('装备ID有误');
        $gears = json_encode($gears);
        $info = compact('name', 'gears');
        if($action == 'insert')
        {
            $tid = $this->db->insertRowTable('r_gear_set', $info);
            if($tid)
            {
                $writeRedis = true;
            }
        }
        elseif($action == 'update')
        {
            $tid = common::request('tid', 'P');
            if($tid)
            {
                $info['tid'] = $tid;
                if($this->db->updateRowTable('r_gear_set', $info))
                {
                    $writeRedis = true;
                }
            }
        }
        else{
            exit('参数不正确');
        }
        if(isset($writeRedis) && $writeRedis)
        {
            $redisKey = REDIS_PREFIX.'GearSet_'.$tid;
            foreach (json_decode($gears, true) as $key => $gearId) {
                $this->redis->ZADD($redisKey, $key, $gearId);
            }
        }
        common::go("index.php?c=admin&a=gearSetInfo&type=edit&tid={$tid}");
    }

    /**
     * 群组列表
     * @return [type] [description]
     */
    public function doGroupList(){
        $p = common::request('p', 'G', 1);
        
        $isSearch = common::request('s', 'P','');
        if($isSearch == 'search'){
            $p = 1;
        }
        $groupId = common::request('groupId', 'R','');
        $groupName = common::request('groupName', 'R','');
        $sort = common::request('sort','R','id');
        $order = common::request('order','R','DESC');
        
        $countSql = "select count(*) from r_group order by addtime DESC";
        if(!empty($groupId) && !empty($groupName)){
            $countSql = "select count(*) from r_group where gid = '$groupId' and name like '%$groupName$'";
        }else{
            if(!empty($groupId)){
                $countSql = "select count(*) from r_group where gid = '$groupId'";
            }
            if(!empty($groupName)){
                $countSql = "select count(*) from r_group where  name like '%$groupName%'";
            }
        }

        $search = compact('groupId','groupName','sort','order');
        $offset = 20;
        $num = $this->db->getone($countSql);


        $parameter = "&groupName=".$groupName."&groupId=".$groupId;
        //分页
        require FILE . 'lib/page.class.php';
        $page = new Page($num, $offset,$parameter);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);

        $start = ($p - 1) * $offset;

        $where = "1";
        $sql = "select g.* from r_group as g";
        
        if($groupId){
            $where .= " AND g.gid='$groupId'";
        }
        if($groupName){
            $where .= " AND g.name like '%$groupName%'";
        }
        $sql .= " WHERE $where";

        if($sort == 'id' || $sort == 'members' || $sort == 'isDismiss'){
            $sql .= " ORDER BY $sort $order LIMIT $start,$offset";
        }elseif($sort){
            if($sort=='post'){
                $redisKey = REDIS_PREFIX.'groupBypost';
            }elseif($sort=='mileage'){
                $redisKey = REDIS_PREFIX.'groupBymileage';
            }elseif($sort=='activity'){
                $redisKey = REDIS_PREFIX.'groupByactivity';
            }
            if($order=='asc'){
                $ids = $this->redis->zrange($redisKey,$start,$start+$offset);
            }else{
                $ids = $this->redis->zrevrange($redisKey,$start,$start+$offset);
            }
            
            if(is_array($ids)){
                $instr = implode(',',$ids);
                $sql .= " AND g.gid IN({$instr}) ORDER BY INSTR(',{$instr},',CONCAT(',',g.gid,','))";
            }
        }

        $setList = $this->db->getall($sql);
        if($setList)
        {
            foreach ($setList as & $v) {
                $gid = $v['gid'];
                $runList = $this->db->getone("select sum(mileage) as total_mileage from r_group_run where gid = '$gid'");
                $v['total_mileage'] = empty($runList) ? 0 : $runList;

                $uid = $v['uid'];
                $userList = $this->db->getone("select nickname from r_user where uid = '$uid'");
                $v['username'] = empty($userList) ? '无' : $userList;
                $v['postNum'] = $this->db->getOne("select count(1) from r_group_news where gid=$gid");
                $v['activityCount'] = $this->db->getOne("select count(1) from r_group_activity where gid = $gid");
                $ac = $this->redis->zcard(REDIS_PREFIX."GroupActivity_".$gid);
                $v['officeActivityCount'] = isset($ac)?$ac-$v['activityCount']:0;
            }
        }
        $this->view->assign('list', $setList);
        $this->view->assign('search', $search);
        $this->view->display('groupList');
    }

    public function dogroupUpdate()
    {
        $gid = intval(common::request('gid', 'R'));
        $groupInfo = $gid ? $this->load('group')->getGroupInfo($gid, TRUE) : [];

        if(common::request('type') == 'json')
        {
            exit(json_encode($groupInfo));
        }

        $isNew = empty($groupInfo);
        !$groupInfo && $groupInfo = [
            'name' => '', 'uid' => '175701', 'slogan' => '', 'header' => '', 'sourceImg' => '',
            'province' => '', 'city' => '', 'addtime' => '', 'isDismiss' => 0, 'is_im' => 1, 
            'isverify' => 0, 'member_limit' => $this->config['group']['maxMember'],
        ];
        $msg = NULL;

        if(common::method() == 'POST')
        {

            $name = common::request('name', 'P');
            $uid = intval(common::request('uid', 'P'));
            $slogan = common::request('slogan', 'P');
            $province = common::request('province', 'P');
            $city = common::request('city', 'P');
            $isverify = intval(common::request('isverify', 'P'));
            $isDismiss = intval(common::request('isDismiss', 'P'));
            $member_limit = intval(common::request('member_limit', 'P'));

            if(!$name || !$uid)
            {
                $msg = '亲，请将群资料填写完整！';
            }
            else
            {
                if($isNew)
                {
                    $this->load('group')->createGroup($uid, $name, $slogan, $province, $city, '[]', $isverify, $isDismiss, $member_limit, FALSE);
                    $msg = '亲，群组已创建成功！';
                }
                else
                {
                    $upGroupInfo = compact('uid', 'name', 'slogan', 'province', 'city', 'isverify', 'isDismiss', 'member_limit');
                    $this->load('group')->setGroupInfo($gid, $upGroupInfo);
                    $groupInfo = $this->load('group')->getGroupInfo($gid, TRUE);
                    $msg = '亲，群组信息已修改成功！';
                }
            }
        }

        $this->view->assign('msg', $msg);
        $this->view->assign('gid', $gid);
        $this->view->assign('groupInfo', $groupInfo);
        $this->view->assign('isNew', $isNew);
        $this->view->display('groupUpdate');
    }

    /*
     * 设为群管理员
     */
    public function dosetGroupAdmin()
    {
        $gid = intval(common::request('gid'));
        $uid = intval(common::request('uid'));

        $this->load('group')->setGroupAdmin($gid, [$uid], TRUE);
        common::go(common::reurl());
    }

    /*
     * 取消群管理员
     */
    public function docancelGoupAdmin()
    {
        $gid = intval(common::request('gid'));
        $uid = intval(common::request('uid'));

        $this->load('group')->cancelGroupAdmin($gid, $uid, TRUE);
        common::go(common::reurl());
    }
    
    /**
     * 删除成员
     */
    public function dodelGroupMember(){
        $gid = common::request('gid', 'G');
        $uid = common::request('uid', 'G');

        $gInfo = $this->load('group')->getGroupInfo($gid);
        if(empty($gInfo) || (isset($gInfo['isDismiss']) && $gInfo['isDismiss'] == 1))
        {
            die('群id有误或已解散，点顶部返回');
        }
        $result = $this->load('groupActivity')->isQuit($gid,$uid);
        if($result){
            die('不是群成员');
        }
        $this->load('groupActivity')->quitAct($uid,$gid);
        $is_success = $this->load('group')->delMember($gid, $this->realUser['uid'], $uid, true);
        common::go(common::reurl());
    }
    
    /*
     * 添加到群组
     */
    public function dojoinGroup(){
        $gid = common::request('gid', 'R');
        $uid = common::request('uid', 'R');
        
        if(empty($gid) || empty($uid)){
            common::go(common::reurl());
        }
        
        $this->load('group')->joinGroup($gid, $uid);
        common::go("?c=admin&a=GroupStatistic&gid=$gid");
    }

    public function dogetUserInfo()
    {
        $uid = intval(common::request('uid', 'R'));

        $userInfo = $uid ? $this->load('client')->getUserInfo($uid) : [];
        $showInfo = $userInfo ? ['nickname' => $userInfo['nickname'], 'header' => $userInfo['header']] : ['nickname' => '', 'header' => ''];

        echo json_encode($showInfo);
    }

    /**
     * 推荐群组列表
     * @return
     */
    public function dogroupRecommendList()
    {
        $p = common::request('p', 'G', 1);
        $msg = common::request('msg', 'G');
        $offset = 20;

        $num = $this->load('admin')->getRecommendGroupNum();

        //分页
        require FILE . 'lib/page.class.php';
        $page = new Page($num, $offset);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);

        $start = ($p - 1) * $offset;
        $sql = "select * from r_group_recommend where is_delete = 0 order by add_time DESC limit $start,$offset";
        $groupList = $this->db->getall($sql);
        if($groupList)
        {
            $this->load('group');
            $this->load('client');
            foreach ($groupList as & $v) {
                $groupInfo = $_ENV['group']->getGroupInfo($v['gid']);
                $userInfo = $_ENV['client']->getUserInfo($groupInfo['uid']);
                $v['name'] = $groupInfo['name'];
                $v['header'] = $groupInfo['header'] ? $groupInfo['header'] : 'static/bootstrap/img/jog_logo.png';
                $v['add_time'] = date("Y-m-d", $v['add_time']);
                $v['city'] = $groupInfo['province'].' '.$groupInfo['city'];
                $v['members'] = $groupInfo['members'];
                $v['createTime'] = date("Y-m-d", $groupInfo['addtime']);
                $v['isDismiss'] = $groupInfo['isDismiss'];
                $v['uid'] = $groupInfo['uid'];
                $v['mileage'] = $this->redis->hget(REDIS_PREFIX.'GRTotal',$v['gid']);
                $v['nickname'] = empty($userInfo) ? '用户已被删除' : $userInfo['nickname'];
            }
        }

        $this->view->assign('groupList', $groupList);
        $this->view->assign('msg', $msg);
        $this->view->display('groupRecommendList');
    }
    /**
     * 加入推荐群组
     * @return
     */
    public function doaddRecommendGroup()
    {
        $gid = common::request('gid', 'R');
        $gid = intval($gid);

        $msg = '';

        $groupInfo = $this->load('group')->getGroupInfo($gid);

        if(empty($groupInfo) || $groupInfo['isDismiss'])
        {
            $msg = '群组不存在或已被解散';
        }
        elseif(isset($groupInfo['members']) && $groupInfo['members'] >= 2000)
        {
            $msg = "该群人数已达上限";
        }
        else
        {
            if($this->load('admin')->addRecommendGroup($gid))
            {
                $this->redis->ZADD(REDIS_PREFIX.'RecGroupList', time(), $gid);
                $msg = '群组:'.$groupInfo['name'].'---加入推荐成功';
            }
            else
            {
                $msg = '群组:'.$groupInfo['name'].'---加入推荐失败';
            }
        }
        common::go('index.php?c=admin&a=groupRecommendList&msg='.urlencode($msg));
        exit;
    }
    /**
     * 移除推荐群组
     * @return
     */
    public function doremRecommendGroup()
    {
        $gid = common::request('gid', 'G');

        $groupInfo = $this->load('group')->getGroupInfo($gid);

        if(empty($groupInfo))
        {
            $msg = '群组不存在';
        }
        else
        {
            if($this->load('admin')->remRecommendGroup($gid))
            {
                $this->redis->ZREM(REDIS_PREFIX.'RecGroupList', $gid);
                $msg = '群组:'.$groupInfo['name'].'---移除推荐成功';
            }
            else
            {
                $msg = '群组:'.$groupInfo['name'].'---移除推荐失败';
            }
        }
        common::go('index.php?c=admin&a=groupRecommendList&msg='.urlencode($msg));
        exit;
    }
    
    /*
     * banner 管理
     */
    public function doBanner(){
        $posi = common::request('posi','G','GroupBanner');
        $banner_mod = $this->load('banner');
        switch($posi){
            case 'bbsFocusPic':
                $banners = $banner_mod->getBbsFocusPic();
                break;
            case 'GroupBanner':
                $banners = $banner_mod->getGroupBanner();
                break;
            case 'gearNewsBanner':
                $banners = $banner_mod->getGearNewsBanner();
                break;
            case 'ActBanner':
                $banners = $banner_mod->getActBanner();
                break;
            case 'userBanner':
                $banners = $banner_mod->getUserBanner();
                break;
            case 'groupBanner2':
                $banners = $banner_mod->getGroupBanner2();
                break;
            case 'actRecBanner':
                $banners = $banner_mod->getActRecBanner();
                break;
            default:
                $banners = $banner_mod->getBanner($posi);
        }
        $posi_arr = [
            //注释为保留字段
            //'bbsFocusPic' => '首页焦点图',
            //'gearNewsBanner' => '装备资讯顶部banner',
            //'ActBanner' => '官方活动广告位',
            'GroupBanner' => '群组焦点图',
            'userBanner' => '用户中心banner',
            'groupBanner2' => '群组首页banner',
            'actRecBanner' => '群组精彩活动banner',
            'init' => '开机',
            'initAnd' => '安卓开机',
            'startRun' => '跑步开始',
            'finishRun' => '跑步结束',
            'bbsBanner' => '有道广告1',
            'activityListBanner' => '有道活动列表',
            'mainButton' => '主按钮',
        ];
        $imgSize = [
            'GroupBanner'=>'',
            'userBanner'=>'710*120',
            'groupBanner2'=>'',
            'actRecBanner'=>'710*120',
            'init'=>'640*1136',
            'initAnd'=>'720*1280',
            'startRun'=>'710*120',
            'finishRun'=>'580x666',
            'bbsBanner'=>'710*120',
            'activityListBanner'=>'710*120',
            'mainButton' => '第一张为背景(1125*150)，后面跟着5张是未选中(75*66)，再后面5张是选中，第三个按钮为圆形(180*182)',
        ];
        
        $urlArr = array(
                    array('name' => '帖子','link' => 'joggers://topic/{topicID}'),
                    array('name' => '板块','link' => 'joggers://topicboard/{boardID}'),
                    array('name' => '标签聚合页面','link' => 'joggers://topictag/{tagID}')
                    );
                    
        $this->view->assign('posi_arr',$posi_arr);
        $this->view->assign('imgSize',$imgSize[$posi]);
        $this->view->assign('posi',$posi);
        $this->view->assign('urlArr', $urlArr);
        $this->view->assign('banners', $banners);
        $this->view->display('banner');
    }
    
    /*
     * 设置banner
     */
    public function dosetBanner(){
        $num = common::request('num','P');
        $num = intval($num);
        $posi = common::request('posi','R');
        if(empty($posi)){
            die('参数错误<a href="index.php?c=admin&a=banner">点击返回</a>');
        }
        $banner_mod = $this->load('banner');
        switch($posi){
            case 'bbsFocusPic':
                $oldBanner = $banner_mod->getBbsFocusPic();
                return;//不处理
                break;
            case 'GroupBanner':
                $oldBanner = $banner_mod->getGroupBanner();
                $path = 'RecGroupBanner';
                break;
            case 'gearNewsBanner':
                $oldBanner = $banner_mod->getGearNewsBanner();
                return;//不处理
                break;
            case 'ActBanner':
                $oldBanner = $banner_mod->getActBanner();
                $path = 'GroupActBanner';
                break;
            case 'userBanner':
                $oldBanner = $banner_mod->getUserBanner();
                $path = $posi;
                break;
            case 'groupBanner2':
                $oldBanner = $banner_mod->getGroupBanner2();
                $path = $posi;
                break;
            case 'actRecBanner':
                $oldBanner = $banner_mod->getActRecBanner();
                $path = $posi;
                break;
            default:
                $oldBanner = $banner_mod->getBanner($posi);
        }

        $newBanner = array();
        $linkArr = common::request('link', 'P');
        $sortArr = common::request('sort','P');
        $startTimeArr = common::request('startTime','P');
        $endTimeArr = common::request('endTime','P');
        for($i = 0; $i <= $num; $i++){
            if(isset($linkArr[$i]))
            {
                $img = $this->load('qiniu')->uploadQiNiuImg('img_'.$i, md5(time().$path.$i));
                if(!$img)
                {
                    $img = isset($oldBanner[$i]) ? $oldBanner[$i]['img'] : '';
                }
                $sort = isset($sortArr[$i]) ? $sortArr[$i] : 0;
                $link = $linkArr[$i];
                $startTime = $startTimeArr[$i];
                $endTime = $endTimeArr[$i];
                $img && $newBanner[] = compact('img','link','sort','startTime','endTime');
            }
        }

        $banner_mod->setBanner($posi,$newBanner);
        common::go('index.php?c=admin&a=banner&posi='.$posi);
    }

    public function doGroupStatisticMemberRun(){


        $gid = common::request('gid', 'R');
        $startDate = common::request('startDate', 'R',date("Y-m-d",time()-3*24*3600));
        $endDate = common::request('endDate', 'R',date('Y-m-d'));
        $p = common::request('p', 'R',1);
        $offset=20;

        $sql="SELECT a.uid,SUM(mileage) AS mileage,
              SUM(elapsedtime) AS  elapsedtime,nickname,header
              FROM r_group_run  AS a LEFT JOIN r_user ON a.uid=r_user.uid
              WHERE  gid={$gid}
              AND a.addTime BETWEEN ".strtotime($startDate)." AND ".strtotime($endDate)."
              GROUP BY a.uid  LIMIT ".$offset*($p-1).",{$offset}";
        $list=$this->db->getAll($sql);

        $sql="SELECT count( DISTINCT uid) FROM r_group_run  WHERE  gid={$gid}
        AND addTime BETWEEN ".strtotime($startDate)." AND ".strtotime($endDate);
        $count=(int)$this->db->getOne($sql);

        require FILE . 'lib/page.class.php';
        $page = new Page($count, $offset,"&startDate={$startDate}&endDate={$endDate}");
        $pageStr = $page->show();

        $gid = common::request('gid', 'G');
        $this->view->assign('gid', $gid);
        $this->view->assign('pageStr', $pageStr);
        $this->view->assign('list', $list);
        $this->view->assign('stime', $startDate);
        $this->view->assign('etime', $endDate);
        $this->view->display('groupStatisticMemberRun');
    }
    
    /**
     * 群组统计 已加入群的用户
     * @return [type] [description]
     */
    public function doGroupStatistic(){
        $gid = common::request('gid', 'G');


        $p = common::request('p', 'G', 1);
        $offset = 20;

        $num = $this->db->getone("select count(*) from r_gmember where gid = '$gid' order by lastupdate DESC");

        //分页
        require FILE . 'lib/page.class.php';
        $page = new Page($num, $offset);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);

        $start = ($p - 1) * $offset;
        $sql = "select * from r_gmember where gid = '$gid' order by addtime DESC limit $start,$offset";
        $setList = $this->db->getall($sql);
        if($setList)
        {
            foreach ($setList as & $v) {
                $uid = $v['uid'];
                $userList = $this->db->getRow("select nickname,header from r_user where uid = '$uid'");
                $v['nickname'] = empty($userList) ? '无' : $userList['nickname'];
                $v['header'] = empty($userList) ? '无' : $userList['header'];
            }
        }

        $this->view->assign('list', $setList);
        $this->view->assign('gid', $gid);
        $this->view->display('groupStatistic');
    }

    /**
     * 群组统计 申请或被邀入群
     * @return [type] [description]
     */
    public function doGroupStatisticCheck(){
        $gid = common::request('gid', 'G');
        $id = common::request('id','G');
        $dotype = common::request('dotype','G',0);
        $uid = common::request('uid','G');
        
        if($id && $uid){
            $gInfo = $this->load('group')->getGroupInfo($gid);
            $maxMember = !empty($gInfo['member_limit']) ? $gInfo['member_limit'] : $this->config['group']['maxMember'];
            if($dotype == 1 && $gInfo['members'] >= $maxMember)
            {
                die('超出人数');
            }
            if(empty($gInfo) || (isset($gInfo['isDismiss']) && $gInfo['isDismiss'] == 1))
            {
                die('群组已解散');
            }
            $curStatus = $this->db->getOne("select status from r_group_add where gid = '{$gid}' and id = '{$id}' and (status < 4 or status = 10) and isShow = 1");
            if($curStatus === false){
                die('状态错误');
            }
            $status = $this->load('group')->dealGroupApply($gid, $uid, $id, $dotype);
            common::go('?c=admin&a=GroupStatisticCheck&gid=10836');
        }
        

        $p = common::request('p', 'G', 1);
        $offset = 20;

        $num = $this->db->getone("select count(*) from r_group_add where gid = '$gid' and status != 0 order by lastupdate DESC");

        //分页
        require FILE . 'lib/page.class.php';
        $page = new Page($num, $offset);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);

        $start = ($p - 1) * $offset;
        $sql = "select * from r_group_add where gid = '$gid' and status != 0 order by addtime DESC limit $start,$offset";
        $setList = $this->db->getall($sql);
        if($setList)
        {
            foreach ($setList as & $v) {
                $uid = $v['uid'];
                $userList = $this->db->getRow("select * from r_user where uid = '$uid'");
                $v['nickname'] = empty($userList) ? '无' : $userList['nickname'];
                $v['header'] = empty($userList) ? '无' : $userList['header'];
            }
        }

        //var_dump($setList);

        $this->view->assign('list', $setList);
        $this->view->assign('gid', $gid);
        $this->view->display('groupStatisticCheck');
    }







    public function doGroupStatisticRunList(){
        $gid = common::request('gid', 'G');

        $p = common::request('p', 'G', 1);
        $offset = 20;

        $num = $this->db->getone("select count(*) from r_group_run where gid = '$gid' order by updatetime DESC");

        //分页
        require FILE . 'lib/page.class.php';
        $page = new Page($num, $offset);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);

        $start = ($p - 1) * $offset;
        $sql = "select * from r_group_run where gid = '$gid' order by updatetime DESC limit $start,$offset";
        $setList = $this->db->getall($sql);
        if($setList)
        {
            foreach ($setList as & $v) {
                $uid = $v['uid'];
                $userList = $this->db->getRow("select * from r_user where uid = '$uid'");
                $v['nickname'] = empty($userList) ? '无' : $userList['nickname'];
                $v['header'] = empty($userList) ? '无' : $userList['header'];
            }
        }


        //var_dump($setList);
        $this->view->assign('list', $setList);
        $this->view->assign('gid', $gid);
        $this->view->display('groupStatisticRunList');
    }


    public function doGroupStatisticRecord(){
        $gid = common::request('gid', 'G');

        $result = $this->load('group')->getBestRecord($gid);
        $result = $result[0] == 0 ? null : $result;
        if($result)
        {
            foreach ($result as & $v) {
                $uid = $v['uid'];
                $userList = $this->db->getRow("select * from r_user where uid = '$uid'");
                $v['nickname'] = empty($userList) ? '无' : $userList['nickname'];
                $v['header'] = empty($userList) ? '无' : $userList['header'];
            }
        }
        $this->view->assign('list', $result);
        $this->view->assign('gid', $gid);
        $this->view->display('groupStatisticRecord');
    }



    /**
     * 这个星期的星期一
     * @param  integer $timestamp           [某个星期的某一个时间戳，默认为当前时间]
     * @param  boolean $is_return_timestamp [是否返回时间戳，否则返回时间格式]
     * @return [type]                       [description]
     */
    function this_monday($timestamp=0,$is_return_timestamp=true){
        static $cache ;
        $id = $timestamp.$is_return_timestamp;
        if(!isset($cache[$id])){
            if(!$timestamp) $timestamp = time();
            $monday_date = date('Ymd', $timestamp-86400*date('w',$timestamp)+(date('w',$timestamp)>0?86400:-/*6*86400*/518400));
            if($is_return_timestamp){
                $cache[$id] = strtotime($monday_date);
            }else{
                $cache[$id] = $monday_date;
            }
        }
        return $cache[$id];

    }

    /**
     * 这个星期的星期天
     * @param  integer $timestamp           [某个星期的某一个时间戳，默认为当前时间]
     * @param  boolean $is_return_timestamp [是否返回时间戳，否则返回时间格式]
     * @return [type]                       [description]
     */
    function this_sunday($timestamp=0,$is_return_timestamp=true){
        static $cache ;
        $id = $timestamp.$is_return_timestamp;
        if(!isset($cache[$id])){
            if(!$timestamp) $timestamp = time();
            $sunday = $this->this_monday($timestamp) + /*6*86400*/518400;
            if($is_return_timestamp){
                $cache[$id] = $sunday;
            }else{
                $cache[$id] = date('Ymd',$sunday);
            }
        }
        return $cache[$id];
    }

    public function doGroupWeek(){


        $wStart = common::request('startWeek', 'R',$this->this_monday(strtotime(time()),false));
        $wEnd = common::request('endWeek', 'R',$this->this_sunday(strtotime(time()),false));

        $weekStart = strtotime($wStart);
        $weekEnd = strtotime($wEnd);


        $field = common::request('field', 'R','mileage');
        $sort = common::request('sort', 'R','desc');

        $searchWeek = array(
            "startWeek" => $wStart,
            "endWeek" => $wEnd,
            "field" => $field,
            "sort" => $sort
        );


        $p = common::request('p', 'G', 1);
        $offset = 20;

        $num = $this->db->getone("select count(*) from r_group order by addtime DESC");

        $parameter = "&startWeek=".$wStart."&endWeek=".$wEnd."&field=".$field."&sort=".$sort;
        //分页
        require FILE . 'lib/page.class.php';
        $page = new Page($num, $offset,$parameter);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);

        $start = ($p - 1) * $offset;

        if($field == 'mileage'){
            if($sort == 'desc'){
                $sql = "select *,(select sum(mileage) as total_mileage from r_group_run where (updatetime >= '$weekStart' and  updatetime<= '$weekEnd') and gid = r_group.gid) as total_num from r_group order by total_num DESC limit $start,$offset";
            }else{
                $sql = "select *,(select sum(mileage) as total_mileage from r_group_run where (updatetime >= '$weekStart' and  updatetime<= '$weekEnd') and gid = r_group.gid) as total_num from r_group order by total_num ASC limit $start,$offset";
            }
        }

        if($field == 'num'){
            if($sort == 'desc'){
                $sql = "select *,(select count(*) as total_mileage from r_group_run where (updatetime >= '$weekStart' and  updatetime<= '$weekEnd') and gid = r_group.gid) as total_num from r_group order by total_num DESC limit $start,$offset";
            }else{
                $sql = "select *,(select count(*) as total_mileage from r_group_run where (updatetime >= '$weekStart' and  updatetime<= '$weekEnd') and gid = r_group.gid) as total_num from r_group order by total_num ASC limit $start,$offset";
            }
        }



        //$sql = "select * from r_group  order by addtime DESC limit $start,$offset";
        $setList = $this->db->getall($sql);
        if($setList)
        {
            foreach ($setList as & $v) {

                $gid = $v['gid'];
                $runList = $this->db->getone("select sum(mileage) as total_mileage from r_group_run where (updatetime >= '$weekStart' and  updatetime<= '$weekEnd') and gid = '$gid'");
                $v['total_mileage'] = empty($runList) ? 0 : $runList;

                $gid = $v['gid'];
                $numList = $this->db->getone("select count(*) as total_num from r_group_run where  (updatetime >= '$weekStart' and  updatetime<= '$weekEnd') and gid = '$gid'");
                $v['total_num'] = empty($numList) ? 0 : $numList;

                $gid = $v['gid'];
                $groupList = $this->db->getone("select name from r_group where gid = '$gid'");
                $v['name'] = empty($groupList) ? 0 : $groupList;
            }
        }

        $this->view->assign('list', $setList);
        $this->view->assign('searchWeek', $searchWeek);
        $this->view->display('groupStatisticWeek');
    }

    public function doGroupMonth(){


        $mStart = common::request('startMonth', 'R',date("Ym",time())."01");
        $mEnd = common::request('endMonth', 'R',date("Ym",strtotime("+1 month"))."01");

        $monthStart = strtotime($mStart);
        $monthEnd = strtotime($mEnd);

        $field = common::request('field', 'R','mileage');
        $sort = common::request('sort', 'R','desc');

        $searchMonth = array(
            "startMonth" => $mStart,
            "endMonth" => $mEnd,
            "field" => $field,
            "sort" => $sort
        );


        $month = substr($mStart, 0, 4) . '-' . substr($mStart, 4, 2);

        $p = common::request('p', 'G', 1);
        $offset = 20;

        $num = $this->db->getone("select count(*) from r_group order by addtime DESC");

        $parameter = "&startMonth=".$mStart."&endMonth=".$mEnd."&field=".$field."&sort=".$sort;
        //分页
        require FILE . 'lib/page.class.php';
        $page = new Page($num, $offset,$parameter);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);

        $start = ($p - 1) * $offset;




        if($field == 'mileage'){
            if($sort == 'desc'){
                $sql = "select *,(select sum(mileage) as total_mileage from r_group_run where (updatetime >= '$monthStart' and  updatetime<= '$monthEnd') and gid = r_group.gid) as total_num from r_group order by total_num DESC limit $start,$offset";
            }else{
                $sql = "select *,(select sum(mileage) as total_mileage from r_group_run where (updatetime >= '$monthStart' and  updatetime<= '$monthEnd') and gid = r_group.gid) as total_num from r_group order by total_num ASC limit $start,$offset";
            }
        }

        if($field == 'num'){
            if($sort == 'desc'){
                $sql = "select *,(select count(*) as total_mileage from r_group_run where (updatetime >= '$monthStart' and  updatetime<= '$monthEnd') and gid = r_group.gid) as total_num from r_group order by total_num DESC limit $start,$offset";
            }else{
                $sql = "select *,(select count(*) as total_mileage from r_group_run where (updatetime >= '$monthStart' and  updatetime<= '$monthEnd') and gid = r_group.gid) as total_num from r_group order by total_num ASC limit $start,$offset";
            }
        }

        //$sql = "select * from r_group  order by addtime DESC limit $start,$offset";
        $setList = $this->db->getall($sql);
        if($setList)
        {
            foreach ($setList as & $v) {

                $gid = $v['gid'];
                $runList = $this->db->getone("select sum(mileage) as total_mileage from r_group_run where (updatetime >= '$monthStart' and  updatetime<= '$monthEnd') and gid = '$gid'");
                $v['total_mileage'] = empty($runList) ? 0 : $runList;

                $gid = $v['gid'];
                $numList = $this->db->getone("select count(*) as total_num from r_group_run where (updatetime >= '$monthStart' and  updatetime<= '$monthEnd') and gid = '$gid'");
                $v['total_num'] = empty($numList) ? 0 : $numList;

                $gid = $v['gid'];
                $groupList = $this->db->getone("select name from r_group where  gid = '$gid'");
                $v['name'] = empty($groupList) ? 0 : $groupList;


                $gid = $v['gid'];
                $targetList = $this->db->getone("select target from r_group_target where gid = '$gid' and r_group_target.month = '$month'");
                $v['target'] = empty($targetList) ? 0 : $targetList;

                $v['target_pct'] = $v['target'] != 0 ? round(($v['total_mileage']/$v['target'])*100) . "%" ."(".$v['total_mileage']."/". $v['target'].")" : "100%";

                $gid = $v['gid'];
                $stargetList = $this->db->getone("select count(*) as single_target from r_user_target where gid = '$gid' and r_user_target.month = '$month'");
                $v['starget'] = empty($stargetList) ? 0 : $stargetList;
            }
        }

        $this->view->assign('list', $setList);
        $this->view->assign('searchMonth', $searchMonth);
        $this->view->assign('month', $month);
        $this->view->display('groupStatisticMonth');
    }


    public function doGroupPersionTarget(){

        $month = common::request('month', 'G');

        $gid = common::request('gid', 'G');

        $p = common::request('p', 'G', 1);
        $offset = 20;

        $num = $this->db->getone("select count(*) from r_user_target where gid='$gid' and r_user_target.month = '$month' order by addtime DESC");

        //分页
        require FILE . 'lib/page.class.php';
        $parameter = "&month=".$month;

        $page = new Page($num, $offset, $parameter);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);

        $start = ($p - 1) * $offset;
        $sql = "select * from r_user_target where gid='$gid' and r_user_target.month = '$month'  order by addtime DESC limit $start,$offset";
        $setList = $this->db->getall($sql);
        if($setList)
        {
            foreach ($setList as & $v) {
                $uid = $v['uid'];
                $userList = $this->db->getRow("select * from r_user where uid = '$uid'");
                $v['nickname'] = empty($userList) ? '无' : $userList['nickname'];
                $v['header'] = empty($userList) ? '无' : $userList['header'];


                $uid = $v['uid'];
                $userDataList = $this->db->getone("select sum(mileage) as total_mileage from r_data where uid = '$uid'");
                $v['total_mileage'] = empty($userDataList) ? 0 : $userDataList;
            }
        }

        $this->view->assign('list', $setList);
        $this->view->display('groupPersonTarget');
    }
    /**
     * 跑步日志列表
     */
    public function dorunLogList()
    {
        $path = $this->config['log-dir'].'runlog/';
        $handle = opendir($path);
        $fileList = array();
        while (false !== ($file = readdir($handle)))
        {
            if(!in_array($file, array('.','..')))
            {
                $fileList[] = array('name' => $file,
                                    'size' => intval(filesize($path.$file))
                                );
            }
        }
        closedir($handle);

        $this->view->assign('list', $fileList);
        $this->view->display('runlog');
    }
    /**
     * 跑步日志下载
     */
    public function dorunLogDown()
    {
        $file_name = common::request('file', 'G');
        $path = $this->config['log-dir'].'runlog/';

        header("Content-type:text/html;charset=utf-8");
        //用以解决中文不能显示出来的问题
        $file_name = iconv("utf-8","gb2312",$file_name);
        $file_path = $path.$file_name;
        //首先要判断给定的文件存在与否
        if(!file_exists($file_path)){
            echo "没有该文件文件";
            return ;
        }
        $fp = fopen($file_path,"r");
        $file_size = filesize($file_path);
        //下载文件需要用到的头
        Header("Content-type: application/octet-stream");
        Header("Accept-Ranges: bytes");
        Header("Accept-Length:".$file_size);
        Header("Content-Disposition: attachment; filename=".$file_name);
        $buffer=1024;
        $file_count=0;
        //向浏览器返回数据
        while(!feof($fp) && $file_count<$file_size){
            $file_con=fread($fp,$buffer);
            $file_count+=$buffer;
            echo $file_con;
        }
        fclose($fp);
        exit;
    }
    /**
     * 帖子图片列表
     */
    public function dopostImgList()
    {
        $p = common::request('p', 'G', 1);
        $offset = 20;
        $p = intval($p);

        $num = $this->load('admin')->getTotalPostNumWithImg();

        //分页
        require FILE . 'lib/page.class.php';
        $page = new Page($num, $offset);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);

        $postList = $_ENV['admin']->getPostWithImg($p, $offset);
        $list = array();
        if($postList)
        {
            foreach ($postList as $post)
            {
                $postImg = @json_decode($post['sourceImg'], true);
                if(empty($postImg))
                {
                    continue;
                }
                $userInfo = $this->load('client')->getUserInfo($post['uid']);
                if($userInfo)
                {
                    foreach ($postImg as $img)
                    {
                        $list[] = array('img' => $img,
                                        'uid' => $post['uid'],
                                        'header' => $userInfo['header'],
                                        'nickname' => $userInfo['nickname'],
                            );
                    }
                }
            }
        }

        $this->view->assign('list', $list);
        $this->view->display('postImgList');
    }
    /**
     * 用户贴子图片列表
     */
    public function dopostImgListbyUser()
    {
        $uid = common::request('uid', 'G');
        $p = common::request('p', 'G', 1);

        $offset = 20;
        $p = intval($p);

        $num = $this->load('admin')->userTotalPostNumWithImg($uid);

        //分页
        require FILE . 'lib/page.class.php';
        $page = new Page($num, $offset);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);

        $list = array();
        $postList = $this->load('admin')->userPostImgList($uid, $p, $offset);
        if($postList)
        {
            $userInfo = $this->load('client')->getUserInfo($uid);
            foreach ($postList as $v) {
                if(common::is_json($v['sourceImg']))
                {
                    foreach (json_decode($v['sourceImg'], true) as $img) {
                        $list[] = array('img' => $img,
                                        'uid' => $uid,
                                        'header' => $userInfo['header'],
                                        'nickname' => $userInfo['nickname'],
                            );
                    }
                }
            }
        }

        $this->view->assign('list', $list);
        $this->view->display('postImgList');
    }
    /**
     * 推荐好友 添加/移除 用户-图片到备选列表
     */
    public function dofriendRecAddAlternate()
    {
        require_once FILE.'../web/static/kindeditor/php/JSON.php';
        $json = new Services_JSON();

        $uid = common::request('uid', 'G');
        $img = common::request('img', 'G');
        $selected = common::request('selected', 'G');

        $error = 0;
        $message = '';

        $res = $this->load('admin')->friendRecAddAlternate($uid, $img, $selected != false);

        if($res === false)
        {
            $error = 1;
            $message = '操作失败';
        }
        else if($res === 2)
        {
            $error = 2;
            $message = '该图片已经是被推荐图片';
        }
        echo $json->encode(array('err' => $error, 'message' => $message));
        exit;
    }
    /**
     * 推荐好友 选定的用户-图片列表
     */
    public function dofriendRecAlternateList()
    {
        $p = common::request('p', 'G', 1);
        $offset = 20;
        $p = intval($p);

        $num = $this->load('admin')->friendRecAlternateNum();

        //分页
        require FILE . 'lib/page.class.php';
        $page = new Page($num, $offset);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);

        $userList = $_ENV['admin']->friendRecAlternateList($p, $offset);
        $list = array();
        if($userList)
        {
            foreach ($userList as & $v)
            {
                $userInfo = $this->load('client')->getUserInfo($v['uid']);
                $v['nickname'] = isset($userInfo['nickname']) ? $userInfo['nickname'] : '不知道这是谁';
                $v['header'] = isset($userInfo['header']) ? $userInfo['header'] : '';
            }
        }

        $this->view->assign('userList', $userList);
        $this->view->display('friendRecAlternateList');
    }

    /**
     * 推荐好友列表
     */
    public function dofriendRecList()
    {
        $msg = common::request('msg', 'G','');
        $reclist = array();
        $uids = $this->load('friends')->getRecommendFriendList(0, 0);

        if($uids)
        {
            $total = count($uids);
            foreach ($uids as $k => $uid)
            {
                $userInfo = $this->load('client')->getUserInfo($uid);
                if($userInfo)
                {
                    $reclist[] = array('uid' => $uid,
                                       'header' => $userInfo['header'],
                                       'nickname' => $userInfo['nickname'],
                                       'imgs' => $_ENV['friends']->getRecFriendImg($uid),
                                       'endUl' => (($k != 0 && $k%3 == 2) || $total-$k == 1) ? 1 : 0
                        );
                }
                else
                {
                    $this->load('admin')->remRecFriend($uid);
                }
            }
        }
        $this->view->assign('msg', $msg);
        $this->view->assign('reclist', $reclist);
        $this->view->display('friendRecList');
    }
    /**
     * 添加到推荐好友列表中
     */
    public function dosetRecFriend()
    {
        $uid = common::request('uid', 'P');
        $images = common::request('images', 'P');

        $uid = intval($uid);
        $images = trim($images);
        $img = array();

        require_once FILE.'../web/static/kindeditor/php/JSON.php';
        $json = new Services_JSON();

        $msg = '';
        $err = 0;

        $result = array('msg' => & $msg, 'err' => & $err);

        $images = explode(',', $images);

        if(empty($images) || count($images) != 3)
        {
            $err = 1;
            $msg = '请选择正确数量的图片';

            echo $json->encode($result);
            exit;
        }

        $this->load('bbs');
        $imgHost = $this->load('qiniu')->getQNHost();

        foreach ($images as $sourceImg)
        {
            if(stripos($sourceImg, $imgHost) === false)
            {
                $err = 3;
                $msg = '无法处理选取的图片：'.$sourceImg;
                break;
            }
            $imgInfo = common::getContents($sourceImg.'?imageInfo');

            if(common::is_json($imgInfo))
            {
                $imgInfo = json_decode($imgInfo, true);

                if(isset($imgInfo['error']))
                {
                    $msg = '获取图片信息失败：'.$sourceImg;
                    break;
                }
                $newImgName = 'RF'.substr($sourceImg, strrpos($sourceImg, '/')+1);
                $recImg = $_ENV['bbs']->qiNiuCropImg($sourceImg, array($imgInfo['width'], $imgInfo['height']), $newImgName, '400x400');
                if(!$recImg)
                {
                    $err = 2;
                    $msg = '处理图片失败：'.$sourceImg;
                    break;
                }
                $img[] = compact('sourceImg', 'recImg');
            }
            else
            {
                $err = 3;
                $msg = '获取不到图片信息';
                break;
            }
        }

        if(!$msg)
        {

            if($this->load('admin')->setRecommendFriendList($uid) !== false)
            {
                $this->load('admin')->setRecFriendImg($uid, $img);
            }
        }

        echo $json->encode($result);
        exit;
    }
    /**
     * 将用户从推荐好友列表中移除
     */
    public function doremRecFriend()
    {
        require_once FILE.'../web/static/kindeditor/php/JSON.php';
        $json = new Services_JSON();

        $uid = common::request('uid', 'G');
        $error = 0;
        $message = '';
        if(!$this->load('admin')->remRecFriend($uid))
        {
            $error = 1;
            $message = '操作失败';
        }
        echo $json->encode(array('err' => $error, 'message' => $message));
        exit;
    }
    /**
     *   热门帖子列表
     */
    public function dotopHotPostList()
    {
        $v = common::request('v','G',2.4);
        // $p = common::request('p', 'G', 1);
        $fresh = common::request('fresh', 'G', 0);
        $curPage = common::request('p','G',1);
        $newId = common::request('newid','G',0);
        $curPage == 1 && $newId = 0;
        $hotPost = array();
        $hotPostIgnore = array();

        $bestPostKey = REDIS_PREFIX.'BbsBestPost';


        if($fresh)
        {
            switch ($v)
            {
                case 2.4:
                    $this->load('bbs')->updateTopHotPost();
                    break;
                case 2.5:
                    $this->load('bbs')->updateHomeBestPost();
                    break;
                default:
                    # code...
                    break;
            }

        }
        switch ($v) {
            case 2.4:
                $hotPostIds = $this->load('bbs')->getTopHotPost();
                $ignorePostIds = $this->load('bbs')->getTopHotIgnore();
                break;
            case 2.5:
                $hotPostIds = $this->load('bbs')->getHomeBestPostList($newId);
                $ignorePostIds = $this->load('bbs')->getHomeBestPostIgnore();
                break;

            default:
                # code...
                break;
        }
        $pId = 0;

        if(!empty($hotPostIds))
        {

            foreach ($hotPostIds as $postId) {
                $postInfo = $_ENV['bbs']->getPostInfo($postId);
                $pId = $postId;

                if(!empty($postInfo) &&!empty( $postInfo['is_show']))
                {
                    $userInfo = $this->load('client')->getUserInfo($postInfo['uid']);
                    if(!empty($userInfo))
                    {
                     $hotPost[] = array('news_id'    => $postInfo['news_id'],
                                      'title'       => $postInfo['title'],
                                      'board'       => $postInfo['board'],
                                      'tag'         => $postInfo['tag'],
                                      'short_desc'  => $postInfo['short_desc'],
                                      'thumb_img'   => $postInfo['thumb_img'],
                                      'uid'         => $postInfo['uid'],
                                      'header'      => $userInfo['header'],
                                      'nickname'    => $userInfo['nickname'],
                                      'add_time'    => $postInfo['add_time'],
                                      'lastupdate'  => $postInfo['lastupdate'],
                                      'loves'       => $postInfo['loves'],
                                      'total_comment'  => $postInfo['total_comment'],
                                      'hotNum'      => $this->redis->ZSCORE($bestPostKey,$postId)
                        );
                   }
                }
            }
        }


        if(!empty($ignorePostIds))
        {
            foreach ($ignorePostIds as $postId) {
                $postInfo = $_ENV['bbs']->getPostInfo($postId);
                if(!empty($postInfo) && $postInfo['is_show'])
                {
                    $userInfo = $this->load('client')->getUserInfo($postInfo['uid']);

                    $hotPostIgnore[] = array('news_id'    => $postInfo['news_id'],
                                      'title'       => $postInfo['title'],
                                      'board'       => $postInfo['board'],
                                      'tag'         => $postInfo['tag'],
                                      'short_desc'  => $postInfo['short_desc'],
                                      'thumb_img'   => $postInfo['thumb_img'],
                                      'uid'         => $postInfo['uid'],
                                      'header'      => $userInfo['header'],
                                      'nickname'    => $userInfo['nickname'],
                                      'add_time'    => $postInfo['add_time'],
                                      'lastupdate'  => $postInfo['lastupdate'],
                                      'loves'       => $postInfo['loves'],
                                      'total_comment'  => $postInfo['total_comment'],
                                      'hotNum'      => $this->redis->ZSCORE($bestPostKey,$postId)
                        );
                }
            }
        }

        $totalRows = $this->redis->ZSIZE($bestPostKey);
        $listRow = 20;
        $query = "&newid=$pId";
        require FILE . 'lib/page.class.php';
        $page = new Page($totalRows,$listRow,$query);
        $pageStr = $page->show();
        $this->view->assign('pageStr',$pageStr);
        $this->view->assign('postv',$v);
        $this->view->assign('postList', $hotPost);
        $this->view->assign('hotPostIgnore', $hotPostIgnore);
        $this->view->display('postHotList');
    }
    /**
     *   屏蔽热门帖子
     */
    public function doignoreHotPost()
    {
        $postId = common::request('postId', 'G');
        $postId = intval($postId);

        $code = 0;
        $msg = '成功';
        $rel = array('cd' => & $code, 'msg' => & $msg);

        if($this->load('admin')->isHotPost($postId))
        {
            if($_ENV['admin']->ignoreHotPost($postId) == false)
            {
                $code = 2;
                $msg = '处理失败';

            }
        }
        else
        {
            $code = 1;
            $msg = '该帖子非热门帖';
        }

        exit(json_encode($rel));
    }
    /**
     *   取消屏蔽热门帖子
     */
    public function docancleIgnoreHotPost()
    {
        $postId = common::request('postId', 'G');
        $postId = intval($postId);
        $code = 0;
        $msg = '成功';
        $rel = array('cd' => & $code, 'msg' => & $msg);

        if($this->load('admin')->cancleIgnoreHotPost($postId) == false)
        {
            $code = 1;
            $msg = '处理失败';
        }

        exit(json_encode($rel));
    }
    /*******2.5.0热门首页***********/
     /**
     *   屏蔽热门帖子
     */
    public function doignoreHotPost2()
    {
        $postId = common::request('postId', 'G');
        $postId = intval($postId);

        $code = 0;
        $msg = '成功';
        $rel = array('cd' => & $code, 'msg' => & $msg);

        if($this->load('admin')->isHotPost2($postId))
        {
            if($_ENV['admin']->ignoreHotPost2($postId) == false)
            {
                echo "123";
                $code = 2;
                $msg = '处理失败';

            }
        }
        else
        {
            $code = 1;
            $msg = '该帖子非热门帖';
        }

        exit(json_encode($rel));
    }
    /**
     *   取消屏蔽热门帖子
     */
    public function docancleIgnoreHotPost2()
    {
        $postId = common::request('postId', 'G');
        $postId = intval($postId);

        $code = 0;
        $msg = '成功';
        $rel = array('cd' => & $code, 'msg' => & $msg);

        if($this->load('admin')->cancleIgnoreHotPost2($postId) == false)
        {
            $code = 1;
            $msg = '处理失败';
        }

        exit(json_encode($rel));
    }
    /*******2.5.0热门首页结束***********/
    /**
     * 消息记录
     * @return [type] [description]
     */
    public function doMessageRecord(){

        $p = common::request('p', 'G', 1);

        $source_id = common::request('fromname', 'R');

        $target_id = common::request('toname', 'R');

        $is_search = common::request('search', 'R');

        if("search" == $is_search){
            $p = 1;
        }

        if(!empty($source_id) && !empty($target_id)){
            $countSql = "select count(id) from r_message_record where source_id = '$source_id' and target_id = '$target_id' and  is_send = 1 and is_before = 0 and category in ('1','2','3')";
        }else if(!empty($source_id)){
            $countSql = "select count(id) from r_message_record where source_id = '$source_id' and is_send = 1 and is_before = 0 and category in ('1','2','3')";
        }else if(!empty($target_id)){
            $countSql = "select count(id) from r_message_record where target_id = '$target_id' and is_send = 1 and is_before = 0 and category in ('1','2','3')";
        }else{
            $countSql = "select count(id) from r_message_record where is_send = 1 and is_before = 0 and category in ('1','2','3')";
        }

        $offset = 10;
        //$num = $this->db->getone('select count(id) from r_message_record where is_send = 1 and is_before = 0 and category in ("1","2","3")');

        $num = $this->db->getone($countSql);
        //分页
        require FILE . 'lib/page.class.php';

        $parameter = "&fromname=".$source_id."&toname=".$target_id;

        $page = new Page($num, $offset,$parameter);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);

        $start = ($p - 1) * $offset;

        if(!empty($source_id) && !empty($target_id)){
            $listSql = "select * from r_message_record where source_id = '$source_id' and target_id = '$target_id' and is_send = 1 and is_before = 0 and category in ('1','2','3') order by id desc limit $start,$offset";
        }else if(!empty($source_id)){
            $listSql = "select * from r_message_record where source_id = '$source_id' and is_send = 1 and is_before = 0 and category in ('1','2','3') order by id desc limit $start,$offset";
        }else if(!empty($target_id)){
            $listSql = "select * from r_message_record where target_id = '$target_id' and is_send = 1 and is_before = 0 and category in ('1','2','3') order by id desc limit $start,$offset";
        }else{
            $listSql = "select * from r_message_record where is_send = 1 and is_before = 0 and category in ('1','2','3') order by id desc limit $start,$offset";
        }

        //$sql = "select * from r_message_record where is_send = 1 and is_before = 0 and category in ('1','2','3') order by id desc limit $start,$offset";
        $msgList = $this->db->getAll($listSql);


        $allInfo = array();
        foreach ($msgList as $key => $item) {
            if(in_array($item['category'], array('1','2','3'))){
                $allInfo[$key]['id'] = $item['id'];
                $allInfo[$key]['time'] = $item['time'];
                $allInfo[$key]['status_time'] = $item['status_time'];
                $allInfo[$key]['status'] = $item['status'];
                $allInfo[$key]['type'] = $item['type'];
                $allInfo[$key]['is_before'] = $item['is_before'];

                $allInfo[$key]['target_id'] = $item['target_id'];

                $allInfo[$key]['source_id'] = $item['source_id'];
                if(in_array($item['descType'],array('F1','F2','N1','N2','N3','N4',"N5",'N6','N7','N8'))){

                    if("F1" == $item['descType']){
                        $allInfo[$key]['messageContent'] = "添加你为好友";
                        $allInfo[$key]['conversationType'] = "新的朋友";
                    }

                    if("F2" == $item['descType']){
                        $allInfo[$key]['messageContent'] = "申请好友被验证通过";
                        $allInfo[$key]['conversationType'] = "新的朋友";
                    }

                    if("N1" == $item['descType']){
                        $allInfo[$key]['messageContent'] = "回复了你的帖子";
                        $allInfo[$key]['conversationType'] = "跑步有道";
                    }

                    if("N2" == $item['descType']){
                        $allInfo[$key]['messageContent'] = "喜欢了你的帖子";
                        $allInfo[$key]['conversationType'] = "跑步有道";
                    }

                    if("N3" == $item['descType']){
                        $allInfo[$key]['messageContent'] = "回复了你的回复";
                        $allInfo[$key]['conversationType'] = "跑步有道";
                    }

                    if("N4" == $item['descType']){
                        $allInfo[$key]['messageContent'] = "点亮了你的回复";
                        $allInfo[$key]['conversationType'] = "跑步有道";
                    }
                    if("N5" == $item['descType']){
                        $allInfo[$key]['messageContent'] = "评论了你的活动";
                        $allInfo[$key]['conversationType'] = "群组活动";
                    }
                    if("N6" == $item['descType']){
                        $allInfo[$key]['messageContent'] = "回复了你的活动";
                        $allInfo[$key]['conversationType'] = "群组活动";
                    }
                    if("N7" == $item['descType']){
                        $allInfo[$key]['messageContent'] = "帖子置顶";
                        $allInfo[$key]['conversationType'] = "群组帖子";
                    }
                    if("N8" == $item['descType']){
                        $allInfo[$key]['messageContent'] = "帖子删除";
                        $allInfo[$key]['conversationType'] = "群组帖子";
                    }

                    $targetUserInfo = $this->redis->hgetall(REDIS_PREFIX . 'UserInfo_' . $item['target_id']);
                    $sourceUserInfo = $this->redis->hgetall(REDIS_PREFIX . 'UserInfo_' . $item['source_id']);
                    $allInfo[$key]['sourceName'] = isset($sourceUserInfo['nickname']) ? $sourceUserInfo['nickname'] : "热心人";
                    $allInfo[$key]['sourceHeader'] = isset($sourceUserInfo['header']) ? $sourceUserInfo['header'] : "http://irun.hupu.com/static/bootstrap/img/jog_logo.png";
                    $allInfo[$key]['targetName'] = isset($targetUserInfo['nickname']) ? $targetUserInfo['nickname'] : "热心人";
                    $allInfo[$key]['targetHeader'] = isset($targetUserInfo['header']) ? $targetUserInfo['header'] : "http://irun.hupu.com/static/bootstrap/img/jog_logo.png";
                }
                $content = array(
                                    "G1" => "申请加入群组",
                                    "G2" => "通过你的加入申请",
                                    "G3" =>  "邀请你加入",
                                    "G4" => "同意你的邀请",
                                    "G5" => "已退出群组",
                                    "G6" => "将你移除群组",
                                    "G7" => "群主将群组解散",
                                    "G8" => "将你设置为管理员",
                                    "G9" => "你已被取消管理员",
                                    "G10" => "邀请你加入",
                                    "G11" => "参加活动",
                                    "G12" => "申请加入群组",
                                    "G13" => "取消活动",
                                    "G14" => "退出活动",
                                    "G15" => "活动认领",
                                    "G16" => "成员参加活动",
                                    "G17" => "活动即将开始",//活动开始前2小时
                                    "G18" => "活动结束",//竞赛活动结束
                                    "G19" => "群组转让"

                                );

                if(isset($content[$item['descType']])){
                    $allInfo[$key]['conversationType'] = "群组";
                    $allInfo[$key]['messageContent'] = $content[$item['descType']];
                    $targetUserInfo = $this->redis->hgetall(REDIS_PREFIX . 'UserInfo_' . $item['target_id']);
                    $allInfo[$key]['targetName'] = isset($targetUserInfo['nickname']) ? $targetUserInfo['nickname'] : "热心人";
                    $allInfo[$key]['targetHeader'] = isset($targetUserInfo['header']) ? $targetUserInfo['header'] : "http://irun.hupu.com/static/bootstrap/img/jog_logo.png";
                    $groupInfo = $this->redis->hgetall(REDIS_PREFIX.'GroupInfo_'.$item['source_id']);
                    $allInfo[$key]['sourceName'] = isset($groupInfo['name']) ? $groupInfo['name'] : "热心群";
                    $allInfo[$key]['sourceHeader'] = isset($groupInfo['header']) ? $groupInfo['header'] : "http://irun.hupu.com/static/bootstrap/img/jog_logo.png";
                }
            }
        }
        $this->view->assign('data', $allInfo);
        $this->view->assign('source_id', $source_id);
        $this->view->assign('target_id', $target_id);
        $this->view->display('messageRecord');
    }
    /**
     * 扑妞消息
     * @return [type] [description]
     */
    public function doMessagePuNiu(){

        $p = common::request('p', 'G', 1);

        $target_id = common::request('target_id', '');

        $is_search = common::request('search', 'R');

        $offset = 10;

        if("search" == $is_search){
            $p = 1;
        }


        //$num = $this->db->getone("select count(*) from (select * from r_message_record left join r_user on r_user.uid = r_message_record.`target_id` where r_user.nickname like '%$nickname%' and r_message_record.is_send = 1 and r_message_record.is_before = 0 and r_message_record.category = 4 group by r_message_record.target_id) mr");
        if(!empty($target_id)){
            //$countSql = "select count(*) from r_user ";

            //$countSqlRecord = "select count(*) from r_message_record where send_id = '175701' and category = 4 and target_id = '$target_id' ";
            //$countSqlSync = "select count(*) from r_message_sync where toUserId = '175701' and fromUserId = '$target_id' ";
            $countSql = "select count(*) from ( (select fromUserId as target_id from r_message_sync where toUserId = '175701'  and fromUserId = '$target_id' order by id desc ) UNION (select target_id from r_message_record where send_id = '175701' and category = 4 and target_id = '$target_id' order by id desc ) ) msg";
            $parameter = "&target_id=".$target_id;
            //$countSql = "select count(*) from (select * from r_message_record left join r_user on r_user.uid = r_message_record.`target_id` where  r_message_record.is_send = 1 and r_message_record.is_before = 0 and r_message_record.category = 4 group by r_message_record.target_id) mr ";
        }else{

            //$countSqlRecord = "select count(*) from r_message_record where send_id = '175701' and category = 4 group by target_id ";
            //$countSqlSync = "select fromUserId from r_message_sync where toUserId = '175701' group by fromUserId  ";

            $countSql = "select count(*) from ( (select fromUserId as target_id from r_message_sync where toUserId = '175701' order by id desc ) UNION (select target_id from r_message_record where send_id = '175701' and category = 4 order by id desc ) ) msg";
            $parameter = "";
            //$countSql = "select count(*) from r_user where nickname like '%$nickname%' ";
            //$countSql = "select count(*) from (select * from r_message_record left join r_user on r_user.uid = r_message_record.`target_id` where r_user.nickname like '%$nickname%' and r_message_record.is_send = 1 and r_message_record.is_before = 0 and r_message_record.category = 4 group by r_message_record.target_id) mr ";
        }
        //var_dump($countSql);

        // $numRecord = $this->db->getone($countSqlRecord);
        // $numSync = $this->db->getone($countSqlSync);

        // $num = intval($numRecord) + intval($numSync);

        $num = $this->db->getone($countSql);
        //分页
        require FILE . 'lib/page.class.php';
        $page = new Page($num, $offset,$parameter);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);

        $start = ($p - 1) * $offset;
        //$sql = "select * from r_message_record where is_send = 1 and is_before = 0 and category = 4 group by target_id order by id desc  limit $start,$offset";
        if(empty($target_id)){
            //$countSql = "select count(*) from r_user ";
            //$listSql = "select * from r_user limit $start,$offset";

            $listSql = "(select fromUserId as target_id from r_message_sync where toUserId = '175701' order by id desc ) UNION (select target_id from r_message_record where send_id = '175701' and category = 4 order by id desc ) limit $start,$offset";
            //$listSql = "select * from r_message_record left join r_user on r_user.uid = r_message_record.`target_id` where r_message_record.is_send = 1 and r_message_record.is_before = 0 and r_message_record.category = 4 group by r_message_record.target_id limit $start,$offset";
        }else{
            $listSql = "(select fromUserId as target_id from r_message_sync where toUserId = '175701' and fromUserId = '$target_id' order by id desc ) UNION (select target_id from r_message_record where send_id = '175701' and category = 4 and target_id = '$target_id' order by id desc ) limit $start,$offset";
            //$countSql = "select count(*) from r_user where nickname = $nickname";
            //$listSql = "select * from r_user  where nickname like '%$nickname%' limit $start,$offset";
            //$listSql = "select * from r_message_record left join r_user on r_user.uid = r_message_record.`target_id` where r_user.nickname like '%$nickname%' and r_message_record.is_send = 1 and r_message_record.is_before = 0 and r_message_record.category = 4 group by r_message_record.target_id limit $start,$offset";
        }
        //var_dump($listSql);
        $msgList = $this->db->getAll($listSql);
        // $msgList = $this->db->getAll($sql);
        // $allInfo = array();
        // foreach ($msgList as $key => $item) {

        //     $allInfo[$key]['id'] = $item['id'];
        //     $allInfo[$key]['content'] = $item['content'];
        //     $allInfo[$key]['time'] = $item['time'];
        //     $allInfo[$key]['target_id'] = $item['target_id'];
        //     $allInfo[$key]['is_before'] = $item['is_before'];

        //     $targetUserInfo = $this->redis->hgetall(REDIS_PREFIX . 'UserInfo_' . $item['target_id']);

        //     $allInfo[$key]['targetName'] = isset($targetUserInfo['nickname']) ? $targetUserInfo['nickname'] : "热心人";
        //     $allInfo[$key]['targetHeader'] = isset($targetUserInfo['header']) ? $targetUserInfo['header'] : "http://irun.hupu.com/static/bootstrap/img/jog_logo.png";
        // }
        //
        foreach ($msgList as $key => $item) {

            $targetUserInfo = $this->redis->hgetall(REDIS_PREFIX . 'UserInfo_' . $item['target_id']);
            $msgList[$key]['nickname'] = $targetUserInfo['nickname'];
            $msgList[$key]['uid'] = $targetUserInfo['uid'];
            $msgList[$key]['header'] = $targetUserInfo['header'];


            $sql = "select * from r_message_sync where toUserId = '175701' and fromUserId = '" . $item['target_id']. "' order by id desc ";
            $newMsg = $this->db->getRow($sql);

            $recordSql = "select * from r_message_record where send_id = '175701' and category = 4 and target_id = '" . $item['target_id']. "' order by id desc ";
            $newRecordMsg = $this->db->getRow($recordSql);


            if(!empty($newMsg)){

                $recordTime = empty($newRecordMsg) ? 0 : $newRecordMsg['time'];
                $syncTime = $newMsg['timestamp'] / 1000;

                if($recordTime < $syncTime){

                    if("RC:TxtMsg" == $newMsg['objectName']){
                        $content = json_decode($newMsg['content'],true);
                        $msgList[$key]['newContent'] = $content['content'];
                        $msgList[$key]['type'] = "RC:TxtMsg";
                    }

                    if("RC:ImgMsg" == $newMsg['objectName']){
                        $content = json_decode($newMsg['content'],true);
                        $msgList[$key]['newContent'] = $content['imageUri'];
                        $msgList[$key]['type'] = "RC:ImgMsg";
                    }

                    if("RC:VcMsg" == $newMsg['objectName']){
                        $content = json_decode($newMsg['content'],true);
                        $msgList[$key]['newContent'] = "暂不支持显示";//$content['content'];
                        $msgList[$key]['type'] = "RC:VcMsg";
                    }
                }else{
                    $msgList[$key]['newContent'] = "";
                    $msgList[$key]['type'] = "";
                }
            }else{
                $msgList[$key]['newContent'] = "";
                $msgList[$key]['type'] = "";
            }
        }

        $this->view->assign('target_id', $target_id);
        $this->view->assign('data', $msgList);
        $this->view->display('messagePuNiu');
    }


    public function doMessagePrivate(){
        $p = common::request('p', 'G', 1);

        $source_id = common::request('fromname', 'R');

        $target_id = common::request('toname', 'R');

        $is_search = common::request('search', 'R');

        if("search" == $is_search){
            $p = 1;
        }

        $offset = 10;

        if(!empty($source_id) && !empty($target_id)){
            $countSql = "select COUNT(*) from ( select IF(fromUserId>toUserId,concat(fromUserId,toUserId),concat(toUserId,fromUserId)) AS conversation,id,fromUserId,toUserId,objectName,content,timestamp,channelType from r_message_sync where channelType = 'PERSON' and fromUserId = '{$source_id}' and toUserId = '{$target_id}' group by conversation order by id desc ) sync";
            //$countSql = "select count(*) from r_message_sync where channelType = 'PERSON' and fromUserId = '{$source_id}' and toUserId = '{$target_id}' group by fromUserId, toUserId order by id desc ";
            $parameter = "&fromUserId=".$source_id."&toUserId=".$target_id;
        }else if(!empty($source_id)){
            $countSql = "select COUNT(*) from ( select IF(fromUserId>toUserId,concat(fromUserId,toUserId),concat(toUserId,fromUserId)) AS conversation,id,fromUserId,toUserId,objectName,content,timestamp,channelType from r_message_sync where channelType = 'PERSON' and fromUserId = '{$source_id}' group by conversation order by id desc ) sync ";
            //$countSql = "select count(*) from r_message_sync where channelType = 'PERSON' and fromUserId = '{$source_id}' group by fromUserId, toUserId order by id desc ";
            $parameter = "&fromUserId=".$source_id;
        }else if(!empty($target_id)){
            $countSql = "select COUNT(*) from ( select IF(fromUserId>toUserId,concat(fromUserId,toUserId),concat(toUserId,fromUserId)) AS conversation,id,fromUserId,toUserId,objectName,content,timestamp,channelType from r_message_sync where channelType = 'PERSON' and toUserId = '{$target_id}' group by conversation order by id desc ) sync ";
            //$countSql = "select count(*) from r_message_sync where channelType = 'PERSON' and toUserId = '{$target_id}' group by fromUserId, toUserId order by id desc ";
            $parameter = "&toUserId=".$target_id;
        }else{
            $countSql = "select COUNT(*) from ( select IF(fromUserId>toUserId,concat(fromUserId,toUserId),concat(toUserId,fromUserId)) AS conversation,id,fromUserId,toUserId,objectName,content,timestamp,channelType from r_message_sync where channelType = 'PERSON' group by conversation order by id desc ) sync ";
            //$countSql = "select count(*) from r_message_sync where channelType = 'PERSON' group by fromUserId, toUserId order by id desc ";
            $parameter = "";
        }

        $num = $this->db->getone($countSql);

        require FILE . 'lib/page.class.php';

        $page = new Page($num, $offset, $parameter);

        $pageStr = $page->show();

        $this->view->assign('pageStr', $pageStr);

        $start = ($p - 1) * $offset;

        if(!empty($source_id) && !empty($target_id)){
            $listSql = "select IF(fromUserId>toUserId,concat(fromUserId,toUserId),concat(toUserId,fromUserId)) AS conversation,id,fromUserId,toUserId,objectName,content,timestamp,channelType from r_message_sync where channelType = 'PERSON' and fromUserId = '{$source_id}' and toUserId = '{$target_id}' group by conversation order by id desc limit $start,$offset";
            //$listSql = "select * from r_message_sync where channelType = 'PERSON' and fromUserId = '{$source_id}' and toUserId = '{$target_id}' group by fromUserId, toUserId order by id desc limit $start,$offset";
        }else if(!empty($source_id)){
            $listSql = "select IF(fromUserId>toUserId,concat(fromUserId,toUserId),concat(toUserId,fromUserId)) AS conversation,id,fromUserId,toUserId,objectName,content,timestamp,channelType from r_message_sync where channelType = 'PERSON' and fromUserId = '{$source_id}' group by conversation order by id desc limit $start,$offset";
            //$listSql = "select * from r_message_sync where channelType = 'PERSON' and fromUserId = '{$source_id}' group by fromUserId, toUserId order by id desc limit $start,$offset";
        }else if(!empty($target_id)){
            $listSql = "select IF(fromUserId>toUserId,concat(fromUserId,toUserId),concat(toUserId,fromUserId)) AS conversation,id,fromUserId,toUserId,objectName,content,timestamp,channelType from r_message_sync where channelType = 'PERSON' and toUserId = '{$target_id}' group by conversation order by id desc limit $start,$offset";
            //$listSql = "select * from r_message_sync where channelType = 'PERSON' and toUserId = '{$target_id}' group by fromUserId, toUserId order by id desc limit $start,$offset";
        }else{
            $listSql = "select IF(fromUserId>toUserId,concat(fromUserId,toUserId),concat(toUserId,fromUserId)) AS conversation,id,fromUserId,toUserId,objectName,content,timestamp,channelType from r_message_sync where channelType = 'PERSON' group by conversation order by id desc limit $start,$offset";
            //$listSql = "select * from r_message_sync where channelType = 'PERSON' group by fromUserId, toUserId order by id desc limit $start,$offset";
        }

        $allArr = $this->db->getAll($listSql);

        foreach ($allArr as $key => $item) {

            $fromUserInfo = $this->redis->hgetall(REDIS_PREFIX . 'UserInfo_' . $item['fromUserId']);
            $allArr[$key]['formUserName'] = isset($fromUserInfo['nickname']) ? $fromUserInfo['nickname'] : "热心人";
            $allArr[$key]['formUserHeader'] = isset($fromUserInfo['header']) ? $fromUserInfo['header'] : "http://irun.hupu.com/static/bootstrap/img/jog_logo.png";

            $toUserInfo = $this->redis->hgetall(REDIS_PREFIX . 'UserInfo_' . $item['toUserId']);
            $allArr[$key]['toUserName'] = isset($toUserInfo['nickname']) ? $toUserInfo['nickname'] : "热心人";
            $allArr[$key]['toUserHeader'] = isset($toUserInfo['header']) ? $toUserInfo['header'] : "http://irun.hupu.com/static/bootstrap/img/jog_logo.png";
        }

        $this->view->assign('data', $allArr);
        $this->view->assign('source_id', $source_id);
        $this->view->assign('target_id', $target_id);
        $this->view->display('messageSync');
    }








    /**
     * 单聊页面
     * @return [type] [description]
     */
    public function doMessagePrivateContent(){
        $p = common::request('p', 'G', 1);

        $toUserId = common::request('toUserId','G');

        $fromUserId = common::request('fromUserId','G');


        // $source_id = common::request('fromname', 'R');

        // $target_id = common::request('toname', 'R');

        // $is_search = common::request('search', 'R');

        // if("search" == $is_search){
        //     $p = 1;
        // }

        // if(!empty($source_id) && !empty($target_id)){
        //     $countSql = "select count(*) from r_message_sync where fromUserId = '$source_id' and toUserId = '$target_id' and  toUserId <> 'S10004' and fromUserId <> 'S10004' order by id desc ";
        // }else if(!empty($source_id)){
        //     $countSql = "select count(*) from r_message_sync where fromUserId = '$source_id' and toUserId <> 'S10004' and fromUserId <> 'S10004' order by id desc ";
        // }else if(!empty($target_id)){
        //     $countSql = "select count(*) from r_message_sync where toUserId = '$target_id' and toUserId <> 'S10004' and fromUserId <> 'S10004' order by id desc ";
        // }else{
            $countSql = "select count(*) from r_message_sync where channelType = 'PERSON' and fromUserId in ('{$toUserId}','{$fromUserId}') and toUserId in ('{$toUserId}','{$fromUserId}') order by id desc ";
        //}


        $offset = 10;
        //$num = $this->db->getone("select count(*) from r_message_sync where toUserId <> 'S10004' and fromUserId <> 'S10004' order by id desc ");

        $num = $this->db->getone($countSql);

        //分页
        require FILE . 'lib/page.class.php';
        $page = new Page($num, $offset);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);

        $start = ($p - 1) * $offset;

        $listSql = "select * from r_message_sync where channelType = 'PERSON' and fromUserId in ('{$toUserId}','{$fromUserId}') and toUserId in ('{$toUserId}','{$fromUserId}') order by id desc limit $start,$offset";

        $allArr = $this->db->getAll($listSql);

        $typeArr = array(
            "RC:TxtMsg" => "文本消息",
            "RC:ImgMsg" => "图片消息",
            "RC:VcMsg" => "语音消息",
            "RC:InfoNtf" => "提示小灰条"
        );

        // $infoArr = array();
        foreach ($allArr as $key => $item) {

            $infoArr[$key]['id'] = $item['id'];
            $infoArr[$key]['timestamp'] = $item['timestamp']/1000;
            $infoArr[$key]['type'] = $item['objectName'];
            $infoArr[$key]['typeName'] = $typeArr[$item['objectName']];

            $infoArr[$key]['fromUserId'] = $item['fromUserId'];
            $infoArr[$key]['toUserId'] = $item['toUserId'];

            if("RC:TxtMsg" == $item['objectName']){
                $content = json_decode($item['content'],true);
                $infoArr[$key]['content'] = $content['content'];
            }else if("RC:ImgMsg" == $item['objectName']){
                $content = json_decode($item['content'],true);
                $infoArr[$key]['content'] = $content['imageUri'];
            }else if("RC:VcMsg" == $item['objectName']){
                $content = json_decode($item['content'],true);
                $infoArr[$key]['content'] = "语音消息(暂不处理)";//$content['content'];
            }else if("RC:InfoNtf" == $item['objectName']){
                $infoArr[$key]['content'] = "提示小灰条";
            }else{
                $infoArr[$key]['content'] = "其他类型(暂不处理)";
            }

            $toUserInfo = $this->redis->hgetall(REDIS_PREFIX . 'UserInfo_' . $item['toUserId']);
            $infoArr[$key]['toUserName'] = isset($toUserInfo['nickname']) ? $toUserInfo['nickname'] : "热心人";
            $infoArr[$key]['toUserHeader'] = isset($toUserInfo['header']) ? $toUserInfo['header'] : "http://irun.hupu.com/static/bootstrap/img/jog_logo.png";


            $fromUserInfo = $this->redis->hgetall(REDIS_PREFIX . 'UserInfo_' . $item['fromUserId']);
            $infoArr[$key]['formUserName'] = isset($fromUserInfo['nickname']) ? $fromUserInfo['nickname'] : "热心人";
            $infoArr[$key]['formUserHeader'] = isset($fromUserInfo['header']) ? $fromUserInfo['header'] : "http://irun.hupu.com/static/bootstrap/img/jog_logo.png";
        }

        $this->view->assign('data', $infoArr);
        //$this->view->assign('source_id', $source_id);
        //$this->view->assign('target_id', $target_id);
        $this->view->display('messagePrivateContentSync');
    }

    /**
     * 群消息页面 获取所有群
     * @return [type] [description]
     */
    public function doMessageGroup(){
        $typeArr = array(
            "RC:TxtMsg" => "文本消息",
            "RC:ImgMsg" => "图片消息",
            "RC:VcMsg" => "语音消息",
        );

        $p = common::request('p', 'G', 1);

        $target_id = common::request('toname', 'R');

        $is_search = common::request('search', 'R');

        if("search" == $is_search){
            $p = 1;
        }

        $offset = 10;

        if(!empty($target_id)){
            $countSql = "select count(*) from (select * from r_message_sync where toUserId = '$target_id' and channelType = 'GROUP' group by toUserId order by id desc) sync";
            //$countSql = "select count(*) from r_message_sync where toUserId = '$target_id' and channelType = 'GROUP' group by toUserId order by id desc ";
            $parameter = "&toUserId=".$target_id;
        }else{
            $countSql = "select count(*) from (select * from r_message_sync where channelType = 'GROUP' group by toUserId order by id desc) sync";
            $parameter = "";
        }



        $num = $this->db->getone($countSql);

        require FILE . 'lib/page.class.php';



        $page = new Page($num, $offset,$parameter);

        $pageStr = $page->show();

        $this->view->assign('pageStr', $pageStr);

        $start = ($p - 1) * $offset;

        if(!empty($target_id)){
            $listSql = "select * from r_message_sync where toUserId = '$target_id' and channelType = 'GROUP' group by toUserId order by id desc limit $start,$offset";
        }else{
            $listSql = "select * from r_message_sync where channelType = 'GROUP' group by toUserId order by id desc limit $start,$offset";
        }



        $allArr = $this->db->getAll($listSql);

        foreach ($allArr as $key => $item) {
            $allArr[$key]['typeName'] = $typeArr[$item['objectName']];
            if("RC:TxtMsg" == $item['objectName']){
                $content = json_decode($item['content'],true);
                $allArr[$key]['content'] = $content['content'];
            }

            if("RC:ImgMsg" == $item['objectName']){
                $content = json_decode($item['content'],true);
                $allArr[$key]['content'] = $content['imageUri'];
            }

            if("RC:VcMsg" == $item['objectName']){
                $content = json_decode($item['content'],true);
                $allArr[$key]['content'] = "暂不支持显示";//$content['content'];
            }

            $groupInfo = $this->redis->hgetall(REDIS_PREFIX.'GroupInfo_'.$item['toUserId']);
            $allArr[$key]['toUserName'] = isset($groupInfo['name']) ? $groupInfo['name'] : "热心群";
            $allArr[$key]['toUserHeader'] = isset($groupInfo['header']) && !empty($groupInfo['header']) ? $groupInfo['header'] : "http://irun.hupu.com/static/bootstrap/img/jog_logo.png";

        }

        $this->view->assign('data', $allArr);
        $this->view->assign('target_id', $target_id);
        $this->view->display('messageGroupSync');
    }

    /**
     * 群聊具体内容
     * @return [type] [description]
     */
    public function doMessageGroupContent(){

        $typeArr = array(
            "RC:TxtMsg" => "文本消息",
            "RC:ImgMsg" => "图片消息",
            "RC:VcMsg" => "语音消息",
        );

        $p = common::request('p', 'G', 1);

        $toUserId = common::request('toUserId','G');

        $source_id = common::request('fromname', 'R');

        $is_search = common::request('search', 'R');

        if("search" == $is_search){
            $p = 1;
        }

        if(!empty($source_id)){
            $countSql = "select count(*) from r_message_sync where channelType = 'GROUP' and toUserId = '{$toUserId}' and fromUserId = '$source_id' order by id desc ";
            $parameter = "&fromUserId=".$source_id."&toUserId=".$toUserId;
        }else{
            $countSql = "select count(*) from r_message_sync where channelType = 'GROUP' and toUserId = '{$toUserId}' order by id desc ";
            $parameter = "&toUserId=".$toUserId;
        }

        $offset = 10;

        $num = $this->db->getone($countSql);

        require FILE . 'lib/page.class.php';


        $page = new Page($num, $offset, $parameter);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);

        $start = ($p - 1) * $offset;

        if(!empty($source_id)){
            $listSql = "select * from r_message_sync where channelType = 'GROUP' and toUserId = '{$toUserId}' and fromUserId = '$source_id' order by id desc limit $start,$offset";
        }else{
            $listSql = "select * from r_message_sync where channelType = 'GROUP' and toUserId = {$toUserId} order by id desc limit $start,$offset";
        }

        $allArr = $this->db->getAll($listSql);

        $infoArr = array();

        foreach ($allArr as $key => $item) {

            $infoArr[$key]['id'] = $item['id'];
            $infoArr[$key]['timestamp'] = $item['timestamp']/1000;
            $infoArr[$key]['type'] = $item['objectName'];
            $infoArr[$key]['typeName'] = $typeArr[$item['objectName']];

            $infoArr[$key]['fromUserId'] = $item['fromUserId'];
            $infoArr[$key]['toUserId'] = $item['toUserId'];

            if("RC:TxtMsg" == $item['objectName']){
                $content = json_decode($item['content'],true);
                $infoArr[$key]['content'] = $content['content'];
            }

            if("RC:ImgMsg" == $item['objectName']){
                $content = json_decode($item['content'],true);
                $infoArr[$key]['content'] = $content['imageUri'];
            }

            if("RC:VcMsg" == $item['objectName']){
                $content = json_decode($item['content'],true);
                $infoArr[$key]['content'] = "暂不支持显示";//$content['content'];
            }

            $groupInfo = $this->redis->hgetall(REDIS_PREFIX.'GroupInfo_'.$item['toUserId']);
            $infoArr[$key]['toUserName'] = isset($groupInfo['name']) ? $groupInfo['name'] : "热心群";
            $infoArr[$key]['toUserHeader'] = isset($groupInfo['header']) ? $groupInfo['header'] : "http://irun.hupu.com/static/bootstrap/img/jog_logo.png";


            $userInfo = $this->redis->hgetall(REDIS_PREFIX . 'UserInfo_' . $item['fromUserId']);
            $infoArr[$key]['formUserName'] = isset($userInfo['nickname']) ? $userInfo['nickname'] : "热心人";
            $infoArr[$key]['formUserHeader'] = isset($userInfo['header']) ? $userInfo['header'] : "http://irun.hupu.com/static/bootstrap/img/jog_logo.png";
        }

        $this->view->assign('data', $infoArr);
        $this->view->assign('source_id', $source_id);

        $this->view->display('messageGroupContentSync');
    }

    /**
     * 扑妞消息页面
     * @return [type] [description]
     */
    public function doMessagePuNiuChat(){

        $targetId  = common::request('targetId', 'G');
        $p = common::request('p', 'G', 1);
        $offset = 10;
        $num = $this->db->getone("select count(*) from r_message_record where is_send = 1 and is_before = 0 and category = 4  and target_id = $targetId");

        $num = count($this->toSortOrder($targetId,'',''));
        //分页
        require FILE . 'lib/page.class.php';
        $page = new Page($num, $offset);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);

        $start = ($p - 1) * $offset;
        $sql = "select * from r_message_record where is_send = 1 and is_before = 0 and category = 4 and target_id = $targetId order by id desc  limit $start,$offset ";
        $msgList = $this->db->getAll($sql);

        $targetUserInfo = $this->redis->hgetall(REDIS_PREFIX . 'UserInfo_' . $targetId);


        $targetName = isset($targetUserInfo['nickname']) ? $targetUserInfo['nickname'] : "热心人";
        $targetHeader = isset($targetUserInfo['header']) ? $targetUserInfo['header'] : "http://irun.hupu.com/static/bootstrap/img/jog_logo.png";

        $allInfo = array();
        foreach ($msgList as $key => $item) {
            $allInfo[$key]['id'] = $item['id'];
            $allInfo[$key]['content'] = $item['content'];
            $allInfo[$key]['time'] = $item['time'];
            $allInfo[$key]['is_before'] = $item['is_before'];
        }

        $this->view->assign('data', $this->toSortOrder($targetId,$start,$offset));
        //$this->view->assign('data', $allInfo);
        $this->view->assign('targetId', $targetId);
        $this->view->assign('targetName', $targetName);
        $this->view->assign('targetHeader', $targetHeader);


        $this->view->display('messagePuNiuChat');
    }

    private function toSortOrder($targetId,$start,$offset){
        $sql = "select id,content,time,'to' as stype,'objectName' as  objectName from r_message_record where is_send = 1 and is_before = 0 and category = 4 and target_id = $targetId order by id desc  ";
        $msgList = $this->db->getAll($sql);//20

        $sql = "select id,content,timestamp/1000 as time,'from' as stype,objectName from r_message_sync where fromUserId = $targetId and toUserId = '175701' order by id desc  ";
        $synclist = $this->db->getAll($sql);//24

        $allArr = array_merge($msgList,$synclist);

        if(!empty($allArr)){
            $sort = array(
                    'direction' => 'SORT_DESC', //排序顺序标志 SORT_DESC 降序；SORT_ASC 升序
                    'field'     => 'time',       //排序字段
            );

            $arrSort = array();
            foreach($allArr AS $uniqid => $row){
                foreach($row AS $key=>$value){
                    $arrSort[$key][$uniqid] = $value;
                }
            }

            if($sort['direction']){
                array_multisort($arrSort[$sort['field']], constant($sort['direction']), $allArr);
            }

            foreach ($allArr as $key => $item) {

                if("objectName" != $item['objectName']){
                    if("RC:TxtMsg" == $item['objectName']){
                        $content = json_decode($item['content'],true);
                        $allArr[$key]['content'] = $content['content'];
                    }

                    if("RC:ImgMsg" == $item['objectName']){
                        $content = json_decode($item['content'],true);
                        $allArr[$key]['content'] = $content['imageUri'];
                    }

                    if("RC:VcMsg" == $item['objectName']){
                        $content = json_decode($item['content'],true);
                        $allArr[$key]['content'] = "暂不提供语音查看";
                    }
                }

            }


            if(!empty($offset)){
                $allArr = array_slice($allArr, $start,$offset);
            }
        }

        return $allArr;

    }

    /**
     * 发送扑妞消息
     * @return [type] [description]
     */
    public function doSendPuNiuMessage(){
        $content  = common::request('content', 'P');
        $target_id = common::request('targetId', 'P');
        //$is_all  = common::request('is_all', 'P');

        // if("false" == $is_all){
        //     $result = $this->load('message')->sendPuNiuSystemMessage($target_id,$content);
        // }else{
        //     $result = $this->load('message')->sendBroadcastSystemMessage($content);
        // }
        $result = $this->load('message')->sendPuNiuSystemMessage($target_id,$content);
        echo json_encode(array("result"=>1));
    }

    public function doGetUserImToken(){
        $uid = common::request('targetId', 'P');
        $im_token = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $uid,'im_token');
        echo json_encode(array("im_token"=>$im_token));
    }
    /*
     *  活动详情
    */
    public function doactivityList()
    {
        $p = common::request('p', 'G', 1);
        $p = intval($p);

        //分页
        require FILE . 'lib/page.class.php';
        $listNum = 10;
        $num = $this->load('admin')->getActivityNum();

        $activityList = $_ENV['admin']->getActivityList($p, $listNum);

        $this->load('activity');
        foreach ($activityList as & $v)
        {
            $v['status'] = $_ENV['activity']->getActStatus($v['start_time'], $v['end_time']);
        }

        $page = new Page($num, $listNum);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);
        $this->view->assign('activityList', $activityList);
        $this->view->display('activityList');
    }
    /*
     *  活动详情
    */
    public function doactivityInfo()
    {
        $action = common::request('action', 'G', 'add');

        if($action == 'add')
        {
            $activityInfo = array(
                                    'act_id' => 0,
                                    'title' => '',
                                    'link' => '',
                                    'thumb_img' => '',
                                    'img' => '',
                                    'status' => 0,
                                    'start_time' => $this->time,
                                    'end_time' => $this->time,
                                    'joins' => 0,
                                    'is_show' => 1
                );
            $action = 'insert';
        }
        else
        {
            $act_id = common::request('act_id', 'G', 0);
            $activityInfo = $this->load('activity')->getActivityInfo($act_id);
            if(empty($activityInfo))
            {
                common::go('index.php?c=admin&a=activityInfo');
                exit;
            }
            $action = 'update';
        }

        $this->view->assign('activity', $activityInfo);
        $this->view->assign('action', $action);
        $this->view->display('activityInfo');
    }
    /*
     *  活动添加与编辑
    */
    public function doactivityEdit()
    {
        // 获取参数
        $action = common::request('action', 'P', 'update');

        $title = common::request('title', 'P');
        $link = common::request('link', 'P');
        // $status = common::request('status', 'P');
        $thumb_img = common::request('thumb_img' ,'P');
        $img = common::request('img', 'P');
        $start_time = common::request('start_time', 'P');
        $end_time = common::request('end_time', 'P');
        $is_show = common::request('is_show', 'P');
        $joins = common::request('joins', 'P', 0);
        $joinsAddition = common::request('joins_addition', 'P', 0);

        // 参数校验
        $title = trim($title);
        $link = trim($link);
        $start_time = strtotime($start_time);
        $end_time = strtotime($end_time);
        $is_show = intval($is_show);
        $joins = intval($joins);
        $joins_addition = intval($joinsAddition);

        if(!$title || !$start_time || !$end_time)
        {
            exit('参数不完整');
        }

        if($start_time >= $end_time)
        {
            exit('活动期限有误');
        }
        // 首页缩略图
        $thumb_imgNew = $this->load('qiniu')->uploadQiNiuImg('thumb_imgNew', 'act_thumb'.md5(time().$title));
        $thumb_imgNew && $thumb_img = $thumb_imgNew;
        // 活动图片
        $imgNew = $this->load('qiniu')->uploadQiNiuImg('imgNew', 'act'.md5(time().$title));
        $imgNew && $img = $imgNew;

        $activityInfo = compact('title','link','thumb_img','img','start_time','end_time','is_show','joins','joins_addition');
        if($action == 'update')
        {
            $act_id = common::request('act_id', 'P');
            $act_id = intval($act_id);

            $rel = $_ENV['admin']->updateActivity($act_id, $activityInfo);
        }
        else
        {
            $act_id = $_ENV['admin']->addActivity($activityInfo);
            $rel = $act_id;
        }

        if($rel)
        {
            echo "操作成功，&nbsp;&nbsp;&nbsp;<a href='index.php?c=admin&a=activityInfo&action=edit&act_id={$act_id}'>查看活动详情</a>";
            exit;
        }
        echo "操作失败&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='".$_SERVER['HTTP_REFERER']."'>回到上一页</a>";
        exit;
    }
    /*
     * 更新版块附加模块
    */
    public function doeditBoardAddition()
    {
        $board = common::request('boardId', 'P');
        $id = common::request('id', 'P');
        $name = common::request('name', 'P');
        $img = common::request('img', 'P');
        $description = common::request('description', 'P');
        $link = common::request('link', 'P');
        $is_show = common::request('is_show', 'P');

        $boardInfo = $this->load('bbs')->getBoardInfo($board);
        if(empty($boardInfo))
        {
            exit('版块信息有误');
        }

        if(empty($id))
        {
            exit('附加模块参数有误');
        }
        // 参数
        $this->load('qiniu');
        $this->load('admin');
        foreach ($id as $key => $v)
        {
            $addition = array('id' => $v);

            $addition['name'] = $name[$key];
            $addition['description'] = $description[$key];
            $addition['link'] = $link[$key];
            $addition['is_show'] = $is_show[$key];

            // logo
            $newImg = $_ENV['qiniu']->uploadQiNiuImg('img_'.$key, md5($this->time.$name[$key]));
            $addition['img'] = $newImg ? $newImg : $img[$key];
            // common::pr($addition);
            // 入库保存
            $_ENV['admin']->updateBoardAddition($v, $addition);
        }

        $url = 'index.php?c=admin&a=board&boardId='.$board;
        common::go($url);
        exit;
    }

    public function doClientTotal()
    {
        // 授权用户虎扑帐号ID
        $uids = array(
            'wanglin' => 16306719,
            'xiaoting' => 15251607,
            'yangxinyang' => 5152038,
            'caoliang' => 4232423,
        );

        if(!in_array($this->realUser['uid'], $uids))
        {
            exit('<h3>这里什么都没有的!</h3>');
        }

        $total = $this->load('dataTotal')->getClientTotal();

        $this->view->assign('total', $total);
        $this->view->display('admin_client_total');
    }

    /**
     * 后台管理员管理
     */
    public function doadminList()
    {
        $adminInfo = $this->load('adminList')->getRowByHupuUid($this->realUser['uid']);

        if($adminInfo['gid'])
        {
            exit('<h3>这里什么都没有的!</h3>');
        }

        $ac = common::request('ac');
        !in_array($ac, array('update', 'del', 'list')) && $ac = 'list';

        switch($ac)
        {
            case 'list':

                $admins = $this->load('adminList')->getList();

                $this->view->assign('admins', $admins);
                $this->view->display('admin_adminlist');

                break;

            case 'update':

                $hupuUid = common::request('hupu_uid');
                $hupuUid = intval($hupuUid);
                $msg = NULL;

                $admin = array('hupu_uid' => '', 'hupu_username' => '', 'gid' => 1, 'description' => '');

                if($hupuUid)
                {
                    $admin = $this->load('adminList')->getRowByHupuUid($hupuUid);
                }

                if(common::method() == 'POST')
                {
                    $data = common::multiRequest(array_keys($admin), 'P');
                    $data['hupu_uid'] && $data['hupu_uid'] = intval($data['hupu_uid']);
                    !$data['gid'] && $data['gid'] = 0;
                    $data['gid'] && $data['gid'] = 1;

                    if($data['hupu_uid'] && $data['hupu_username'] && $data['description'])
                    {
                        if($hupuUid)
                        {
                            unset($data['aid'], $data['create_time'], $data['create_hupu_uid']);
                            $this->load('adminList')->update($data);
                            $admin = $this->load('adminList')->getRowByHupuUid($hupuUid);

                            $msg = '修改成功';
                        }
                        else
                        {
                            $data['create_time'] = $this->time;
                            $data['create_hupu_uid'] = $this->realUser['uid'];

                            $this->load('adminList')->insert($data);

                            common::go('./?c=admin&a=adminList');
                        }
                    }
                    else
                    {
                        $msg = '请使用正确的姿式填写内容!';
                    }
                }

                $this->view->assign('msg', $msg);
                $this->view->assign('admin', $admin);
                $this->view->display('admin_adminlist_update');

                break;

            case 'del':

                $hupuUid = common::request('hupu_uid');
                $hupuUid = intval($hupuUid);

                $this->load('adminList')->deleteRowByHupuUid($hupuUid);
                common::go(common::reurl());

                break;
        }
    }

    /**
     * 水印管理
     */
    public function dowatermarks()
    {
        $ac = common::request('ac');
        !in_array($ac, array('update', 'del', 'list')) && $ac = 'list';

        switch($ac)
        {
            case 'list':

                $watermarks = $this->load('watermarks')->getList();

                $this->view->assign('watermarks', $watermarks);
                $this->view->display('admin_watermarks');

                break;

            case 'update':

                $wid = common::request('wid');
                $wid = intval($wid);
                $msg = NULL;

                $watermark = array('wid' => '', 'demo_img' => '', 'material_img' => '');

                if($wid)
                {
                    $watermark = $this->load('watermarks')->getRowByWid($wid);
                }

                if(common::method() == 'POST')
                {
                    $imageExt = array('image/gif', 'image/jpg', 'image/jpeg', 'image/png', 'image/bmp');

                    $data = common::multiRequest(array_keys($watermark), 'P');
                    $data['wid'] && $data['wid'] = intval($data['wid']);

                    if(!empty($_FILES['demo_imgr']) && !$_FILES['demo_imgr']['error'])
                    {
                        if(in_array($_FILES['demo_imgr']['type'], $imageExt))
                        {
                            $data['demo_img'] = $this->load('qiniu')->uploadQiNiuImg('demo_imgr', 'Watermarks'.md5(time() . $_FILES['demo_imgr']['name']));
                        }
                        else
                        {
                            $msg = '图片仅支持：' . implode(', ', $imageExt);
                        }
                    }

                    if(!empty($_FILES['material_imgr']) && !$_FILES['material_imgr']['error'])
                    {
                        if(in_array($_FILES['material_imgr']['type'], $imageExt))
                        {
                            $data['material_img'] = $this->load('qiniu')->uploadQiNiuImg('material_imgr', 'Watermarks'.md5(time() . $_FILES['material_imgr']['name']));
                        }
                        else
                        {
                            $msg = '图片仅支持：' . implode(', ', $imageExt);
                        }
                    }

                    if(!$msg)
                    {
                        if($data['demo_img'] && $data['material_img'])
                        {
                            if($wid)
                            {
                                $this->load('watermarks')->updateRow($wid, $data);
                                $watermark = $this->load('watermarks')->getRowByWid($wid);

                                $msg = '修改成功';
                            }
                            else
                            {
                                $this->load('watermarks')->insertRow($data);

                                common::go('./?c=admin&a=watermarks');
                            }
                        }
                        else
                        {
                            $msg = '请使用正确的姿式填写内容!';
                        }
                    }
                }

                $this->view->assign('msg', $msg);
                $this->view->assign('watermark', $watermark);
                $this->view->display('admin_watermarks_update');

                break;

            case 'del':

                $wid = common::request('wid');
                $wid = intval($wid);

                $this->load('watermarks')->delRowByWid($wid);
                common::go(common::reurl());

                break;
        }
    }
    /**
     * 修正用户单次跑步数据?
     * @param int $did
     * @return boolean
     */
    public function doadchangeRunData()
    {
        $uid = common::request('uid', 'P');
        $did = common::request('did', 'P');
        $mileage = common::request('mileage', 'P');
        $elapsedtime = common::request('elapsedtime', 'P');
        $calorie = common::request('calorie', 'P');
        $upRunData = compact('uid','mileage','elapsedtime','calorie','did');
         if(empty($uid))
        {
          $_ENV['error']->getErrors(201);
          exit;
        }
        if(empty($did))
        {
          $_ENV['error']->getErrors(101);
          exit;
        }
        if($this->db->getOne("select did from r_data where did= '{$did}' and uid = '{$uid}'"))
        {

            if($this->db->updateRowTable('r_data', $upRunData))
              header("Location:index.php?c=admin&a=showHistory&uid=".$uid."&t=1\n");

                exit;
            }
            exit('修改跑步数据失败');
    }

    /**
     * 短信统计
     */
    public function dosmsReport(){
        $p = common::request('p', 'G', 1);
        $num = $this->db->getOne("select count(t.c) from (select count(*) c from r_sms GROUP BY addtime) t ");
        require FILE . 'lib/page.class.php';
        $listNum = 20;
        $page = new Page($num, $listNum);
        $pageStr = $page->show();
        $offset = ($p - 1)*$listNum;
        $sql = "SELECT addtime,count(*) c FROM r_sms GROUP BY addtime ORDER BY addtime DESC LIMIT $offset,$listNum";
        $all = $this->db->getAll($sql);

        $this->loadLib('sms');
        $sms = new Sms();
        $res = json_decode($sms->banlance(),true);
        $this->view->assign('balance', $res['balance']);
        $this->view->assign('pageStr', $pageStr);
        $this->view->assign('info',$all);
        $this->view->display('smsReport');
    }

    /**
     * 发送详情
     */
    public function dosmsDetail(){
        $p = common::request('p','G',1);
        $date = common::request('time','G');
        $num = $this->db->getOne("SELECT count(*) FROM r_sms WHERE addtime='$date'");
        require FILE . 'lib/page.class.php';
        $listNum = 20;
        $page = new Page($num,$listNum);
        $pageStr = $page->show();
        $offset = ($p-1)*$listNum;
        $sql = "SELECT * FROM r_sms WHERE addtime='$date' LIMIT $offset,$listNum";
        $res = $this->db->getAll($sql);
        $map = array(
            1=>'找回密码',
            2=>'其他'
        );
        $this->view->assign('map',$map);
        $this->view->assign('pageStr',$pageStr);
        $this->view->assign('info',$res);
        $this->view->display('smsDetail');
    }


    /**
     * showtime图片集
     */
    public function doadPosition(){
        $urlArr = array(
            array('name' => '帖子','link' => 'joggers://topic/{topicID}')
        );
        $focusImg = $this->load('bbs')->getPosition();
        if(empty($focusImg))
        {
            $focusImg = array(array('pictureUrl'=> '', 'linkUrl'=>'','sort'=>0));
        }
        $this->view->assign('urlArr', $urlArr);
        $this->view->assign('focusImg', $focusImg);
        $this->view->display('adPosition');
    }

    /**
     * 编辑showtime图片集
     */
    public function doeditADPosition(){
        $num = common::request('num','P');
        $num = intval($num);
        $oldPosition = $this->load('bbs')->getPosition();
        $newPositions = array();
        $link = common::request('link', 'P');
        $sort = common::request('sort','P');
        for($i = 0; $i <=$num ; $i++){
            if(isset($link[$i]))
            {
                $pictureUrl = $this->load('qiniu')->uploadQiNiuImg('picture_'.$i, md5(time().'bbsposition_'.$i));
                if(!$pictureUrl && isset($oldPosition[$i]))
                {
                    $pictureUrl = $oldPosition[$i]['pictureUrl'];
                }
                $linkUrl = $link[$i];
                $pictureUrl && $newPosition = compact('pictureUrl','linkUrl');
                //!empty($newPosition) && $this->redis->zadd(REDIS_PREFIX.'bbsADPosition',$sort[$i],json_encode($newPosition));
                if(empty($newPosition)){
                    die('上传失败，<a href="index.php?c=admin&a=adPosition">点击返回</a>');
                }
                $newPositions[$sort[$i]] = json_encode($newPosition);
            }

        }
        
        $this->redis->delete(REDIS_PREFIX.'bbsADPosition');
        foreach($newPositions as $k=>$v){
            $this->redis->zadd(REDIS_PREFIX.'bbsADPosition',$k,$v);
        }
        common::go('index.php?c=admin&a=adPosition');
    }

    public function doapply(){
        if(!$_POST){
            $this->view->display('apply');
        }else{
            $userId = common::request('userId','P');
            $callback = common::request('callback','P');
            if(empty($userId) || empty($callback)){
                die("参数不完整！");
            }
            $randomData = $userId . mt_rand() . mt_rand() . mt_rand() . mt_rand() . microtime(true) . uniqid(mt_rand(), true);

            $appId = substr(hash('sha512', $randomData), 0, 16);
            $secret = MD5(uniqid().$userId);
            $sql = "insert into r_oauth_clients(user_id,client_id,client_secret,redirect_uri) values($userId,'$appId','$secret','$callback')";
            $res = $this->db->query($sql);
            common::go('index.php?c=admin&a=applyList');
        }

    }

    public function doapplyList(){
        $data = $this->db->getAll('select * from r_oauth_clients');
        $this->view->assign('data',$data);
        $this->view->display('applyList');
    }

    /**
     * 回复页面
     */
    public function dorecomment(){
        $id = common::request('news_id','G',0);

        $f_id = common::request('f_id','G');
        $sql = "select uid from r_news_comment where comment_id=$f_id";
        $uid = $this->db->getOne($sql);
        $userInfo = $this->load('client')->getUserInfo($uid);
        $nickname = $userInfo['nickname'];
        $this->view->assign('uid',$uid);
        $this->view->assign('nickname',$nickname);
        $this->view->assign('news_id',$id);
        $this->view->assign('father_id',$f_id);
        $this->view->display('recomment');
    }

    /**
     * 获取马甲用户
     */
    public function dogetUser(){
        $uid = common::request('uid','G','',true);
        $sql = "select uid,nickname,header from r_user where is_robot=1 and (uid like '{$uid}%')";
        $userInfo = $this->db->getAll($sql);
        $reData = array('message'=>'');
        empty($userInfo) && $reData['message'] = "未找到匹配用户！";
        $reData['data'] = $userInfo;
        echo json_encode($reData);
    }

    /**
     * 马甲号列表
     */
    public function dorobotList(){
        $p = common::request('p','G',1);

        require FILE . 'lib/page.class.php';
        $listNum = 20;
        $num = $this->db->getOne('select count(*) from r_user where is_robot=1');
        $page = new Page($num,$listNum);
        $user = $this->load('user')->getRobot($p,$listNum);
        $pageStr = $page->show();
        $this->view->assign('pageStr',$pageStr);
        $this->view->assign('info',$user);
        $this->view->display('robotList');
    }

    /**
     * 添加/更新马甲号
     */
    public function doaddRobot(){
        $uid = common::request('uid','R',0);
        if(empty($_POST)){
            $user = $this->db->getRow("select * from r_user where uid=$uid and is_robot=1");
            $this->view->assign('user',$user);
            $this->view->display('robot');
        }else{
            $nickname = common::request('nickname','P');
            $birthday = common::request('birthday','P','1997-1-1');
            $height = common::request('height',"P",'175');
            $weight = common::request('weight',"P",'65');
            $gender = common::request('gender','P');
            $phone = common::request('phone','P');
            $pwd = md5(common::request('pwd','P'));
            $signature = common::request('signature','P');
            $info = explode("-",$birthday);
            $age = $info['0'];
            $is_robot = 1;
            $info = $this->load('user')->getInfoByPhone($phone);

            $checkNickname = $this->checkNickname($nickname);
            if(empty($uid) && $checkNickname == -3)//昵称重复
            {
                $nickname = $this->load('user')->makeNickname($nickname);
                if(!empty($info)){
                    $this->_go('该手机号已注册！');
                    exit;
                }
            }
            $data = compact('birthday','height','weight','gender','pwd','age','is_robot','signature');
            $nickname && $data['nickname'] = $nickname;
            $phone && $data['phone'] = $phone;
            if(isset($_FILES['header']) && $_FILES['header']['error'] == 0)
            {
                $imgName = md5(common::getHashStr(6).$this->time);

                $header_source = $this->load('qiniu')->uploadQiNiuImg('header', $imgName);

                if($header_source)
                {
                    $newHeader = $this->load('qiniu')->qiniuPersist($header_source, '?imageMogr2/thumbnail/180x180');
                    $newHeader && $header = $newHeader;
                }
                $data['header'] = $header;
                $data['header_source'] = $header_source;
            }
            if(empty($uid)){
                $addime = time();
                $data['addtime'] = $addime;
                $res = $uid = $this->load('user')->insert($data);
            }else{
                $data['uid'] = $uid;
                $res = $this->load('user')->update($data);
            }
            $url ='';
            $mess = "操作失败！";
            if($res){
                $this->redis->sadd(REDIS_PREFIX . 'VipUserList', $uid);//添加到vip列表
                $url = "index.php?c=admin&a=robotList";
                $mess = '操作成功！';
            }
            $this->_go($mess,$url);
        }

    }

    /**
     * 群组认证
     */
    public function doGroupAuth(){
        $p = common::request('p','G',1);

        require FILE . 'lib/page.class.php';
        $s = isset($_POST['status']) ? $_POST['status'] : -1;
        if($s == -1){
            $where = " where 1";
        }else{
            $where = " where status=$s";
        }
        $listNum = 20;
        $num = $this->db->getOne("select count(*) from r_group_auth $where");
        $page = new Page($num,$listNum);
        $offset = ($p-1) * $listNum;
        $res = $this->db->getAll("select * from r_group_auth $where order by add_time desc limit $offset,$listNum");
        $status = array('等待审核',"审核通过","审核失败","认证取消");
        foreach($res as &$item){
            $ginfo = $this->load('group')->getGroupInfo($item['gid']);
            $item['name'] = $ginfo['name'];
            $item['members'] = $ginfo['members'];
            $item['actNum'] = $this->db->getOne("select count(*) from r_group_activity where status != 1 and gid={$item['gid']}");;
            $item['sName'] = $status[$item['status']];
            $item['img'] = json_decode($item['img'],true);
        }
        $pageStr = $page->show();
        $this->view->assign('pageStr',$pageStr);
        $this->view->assign('s',$s);
        $this->view->assign('info',$res);
        $this->view->assign('status',$status);
        $this->view->display('groupAuth');
    }

    /**
     * 认证操作
     */
    public function doauth(){
        $id = common::request('id','R');
        $act = common::request('act',"R");
        if($act == 'pass'){
            $res = $this->db->query("update r_group_auth set status=1 where id = $id");
            $data['msg'] = $res ? "操作成功" : "操作失败";
            $data['code'] = $res ? 200 : 100;
        }else{
            $reason = common::request('reason','P');
            if(empty($reason)){
                $data['msg'] = "请输入原因";
                $data['code'] = -1;
            }else{
                $status = $act == "refuse" ? 2 : 3;
                $res = $this->db->query("update r_group_auth set status=$status,reason='{$reason}' where id = $id");
                $data['msg'] = $res ? "操作成功" : "操作失败";
                $data['code'] = $res ? 200 : 100;
            }

        }
        echo json_encode($data);
    }

    /**
     * 所有群组活动列表
     */
    public function doGroupActivity(){
        $p = common::request('p','G',1);
        require FILE . 'lib/page.class.php';
        $listNum = 20;
        $atype = common::request("type",'G',0);
        $act = common::request('act','R','');
        $free = common::request('free','R','');
        $group = common::request('group','R','');
        $actType = isset($_REQUEST['actType']) ? $_REQUEST['actType'] : '-1';
        $where = " where 1=1";
        $param = '';
        if(!empty($act)){
            $where .= " and ( title like '%$act%' or aid like '%$act%')";
            $param .= "&act=$act";
        }
        if($atype == 1){
            $where .= " and type < 3";
        }else{
            $where .= " and type > 2";
        }
        if($actType != -1 && $actType != ''){
            $where .= " and type = $actType";
            $param .= "&actType=$actType";
        }
        $recAct = $this->redis->zrevrange(REDIS_PREFIX."ACTRecommend",0,-1);
        if(!empty($recAct)){
            $actIds = implode(",",$recAct);
            $where .= " and aid not in($actIds)";
        }
        if(!empty($free)){
            switch($free){
                case 1:
                    $where .= " and cost <=0";
                    break;
                case 2:
                    $where .= " and cost > 0";
            }
            $param .= "&free=$free";
        }
        if(!empty($group)){
            $gids = $this->db->getAll("select gid from r_group where name like '%{$group}%' or gid like '%{$group}%'");
            $gid = [];
            foreach($gids as $info){
                $gid[] = $info['gid'];
            }
            $gid = implode(',',$gid);
            $where .= " and gid in ($gid)";
            $param .= "&group=$group";
        }
        $num = $this->db->getOne("select count(*) from r_group_activity $where");
        $page = new Page($num,$listNum,$param);
        $offset = ($p-1) * $listNum;
        $data = $this->db->getAll("select * from r_group_activity $where order by aid desc limit $offset,$listNum");
        foreach($data as &$item){
            $item['flag'] = intval($this->redis->zscore(REDIS_PREFIX."ACTRecommend",$item['aid'])) > 0 ? 1 : 0;
            if(empty($item['gid'])){
                $gids = $this->redis->sMembers(REDIS_PREFIX."ACTaccept_".$item['aid']);
                $num = 0;
                foreach($gids as $gid){
                    $num += $this->load('groupActivity')->joinNum($gid,$item['aid']);
                }
            }else{
                $num = $this->load('groupActivity')->joinNum($item['gid'],$item['aid']);
            }
            $userInfo = $this->load('client')->getUserInfo($item['uid']);
            $item['joinNum'] = $num;
            $item['name'] = @$userInfo['nickname'];

        }
        $pageStr = $page->show();
        $type = array("自定义活动","目标里程","目标打卡","官方目标","官方打卡","官方自定义");
        $status = array("正常","已取消","已结束");
        $this->view->assign('pageStr',$pageStr);
        $this->view->assign('type',$type);
        $this->view->assign('act',$act);
        $this->view->assign('group',$group);
        $this->view->assign('free',$free);
        $this->view->assign('actType',$actType);
        $this->view->assign('atype',$atype);
        $this->view->assign('status',$status);
        $this->view->assign('list',$data);
        $this->view->display('groupAct');
    }

    /**
     * 添加/编辑活动
     */
    public function doactHandle(){
        $action = common::request("action","R",'add');
        $id = common::request('id','R',0);
        $info = $this->db->getRow("select a.*,b.* from r_group_activity a left join `r_office_activity` b on a.aid=b.aid where a.aid=$id");
        if($action != "update"){
            if(!empty($info)){
                $info['banner'] = json_decode($info['banner'],true);
                $info['aid'] = $id;
            }
            $giftType = [1=>'勋章',2=>'商品'];
            $this->view->assign('giftType',$giftType);
            $this->view->assign('info',$info);
            $this->view->assign('uri',"http://".$this->config['host']."/show/goodsDetail?goods_id={gid}");
            $this->view->display('actInfo');
        }else{
            $title = common::request('title','P');
            $introduce = common::request('introduce','P');
            $type = common::request('type','P');
            $target = common::request('target','P',0);
            $days = common::request('days','P',0);
            $stime = strtotime(common::request('stime','P'));
            $etime = strtotime(common::request('etime','P'));
            $cost = common::request('cost','P','0');
            $url = common::request('url','P','');
            $rule = common::request('rule','P','');
            $short_desc = common::request('short_desc','P','',true);
            $gift_type = common::request('gift_type','P','',true);
            $gift_id = common::request('gift_id','P','',true);
            $link = common::request('link','P','',true);
            $cost_content = common::request('cost_content','P','');
            $extData = [];
            if(!empty($short_desc)){
                $extData['short_desc'] = $short_desc;
            }

            if($gift_type != -1 && empty($gift_id)){
                $this->_go("请输入奖品ID！");
                exit;
            }
            if(empty($cost_content)){
                $this->_go("请输入费用介绍！");
                exit;
            }
            $place = common::request('place','P');
            $img = '';
            if(isset($_FILES['img']) && $_FILES['img']['error'] == 0)
            {
                $imgName = md5(common::getHashStr(6).$this->time);
                $img = $this->load('qiniu')->uploadQiNiuImg('img', $imgName);
            }
            if(empty($img)){
                $img = isset($info['img']) ? $info['img'] : '';
            }
            $banner_img = isset($info['banner'][0]['img']) ? $info['banner'][0]['img'] : '';
            if(isset($_FILES['banner_img']) && $_FILES['banner_img']['error'] == 0){
                $banner_img = $this->load('qiniu')->uploadQiNiuImg('banner_img', md5(time()));
                if(!$banner_img){
                    $banner_img = isset($info['banner'][0]['img']) ? $info['banner'][0]['img'] : '';
                }
            }
            if(empty($title)){
                $this->_go("活动名不能为空！");
                exit;
            }
            if($etime <= $stime || $stime < time()){
                $this->_go("活动时间不正确，请重新选择！");
                exit;
            }
            if($type == 3 && $target <=0){
                $this->_go("目标里程不能为空！");
                exit;
            }
            if($type == 4 && ($target <=0 || $days <= 0) ){
                $this->_go("目标里程或打卡天数不能为空！");
                exit;
            }
            $data = compact('title','introduce','type','target','days','stime','etime','place','img','url');
            if($id > 0){
                $data['aid'] = $id;
            }
            $data['addtime'] = time();
            $data['cost'] = $cost;
            $aid = $this->db->insertRowTable('r_group_activity',$data);
            if(!empty($extData)){
                $extData['aid'] = $aid;
                $extData['addtime'] = time();
                $extData['gift_type'] = $gift_type;
                $extData['gift_id'] = $gift_id;
                $extData['cost_content'] = $cost_content;
                if(!empty($banner_img)){
                    $banner = [['img'=>$banner_img,'link'=>$link]];
                }else{
                    $banner = [];
                }
                $extData['rule'] = $rule;
                !empty($banner) && $extData['banner'] = json_encode($banner);
                $id > 0 && $extData['aid'] = $id;
                $this->db->insertRowTable('r_office_activity',$extData);
            }
            $data = $this->db->getRow("select a.*,b.gift_id,b.gift_type,b.short_desc,b.rule,b.banner,b.cost_content from r_group_activity a left join `r_office_activity` b on a.aid=b.aid where a.aid=$aid");
            $this->redis->hmset(REDIS_PREFIX.'ActivityInfo_'.$aid,$data);
            $id <=0 && $this->redis->lpush(REDIS_PREFIX.'OfficeAct',$aid);//官方活动
            $this->_go("操作成功！","index.php?c=admin&a=GroupActivity");
        }
    }
    
    /*
     * 创建群组活动
     */
    public function dogroupActHandle(){
        $action = common::request("action","R",'add');
        $id = common::request('id','R',0);
        if($action != "update"){
            $info = $this->db->getRow("select a.* from r_group_activity a where a.aid=$id");
            if(!empty($info)){
                $info['banner'] = json_decode($info['banner'],true);
                $info['aid'] = $id;
            }
            $this->view->assign('info',$info);
            $this->view->display('groupActInfo');
        }else{
            $title = common::request('title',"P");
            $stime = strtotime(common::request('stime',"P"));
            $etime = strtotime(common::request('etime',"P"));
            $type = common::request('type',"P");
            $place = common::request('place',"P",'');
            $cost = common::request('free',"P",'0');
            $way = common::request('join',"P",0);
            $introduce = common::request('introduce',"P");
            $is_show = common::request('is_show','P',0);
            $gids = common::request('gids',"P");
            $target = common::request('target','P',0);
            $target2 = common::request('target2','P',0);
            $days = common::request('days','P',0);
            //$city = common::request("city","P",'');
            $city = $place;
            $lat = common::request('lat',"P",0);
            $lng = common::request('lng',"P",0);
            $address = common::request("address",'P');
            $is_collect_info = common::request("is_collect_info",'P',0);
            $collect_ext_name1 = trim(common::request("collect_ext_name1",'P',''));
            $collect_ext_name2 = trim(common::request("collect_ext_name2",'P',''));
            $limit_member_max = common::request('limit_member_max','P',0);
            $system_img = common::request('system_img','P');
            $uid = common::request('uid','P');
            $uid = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$uid, 'uid');
            if(empty($uid) || empty($gids))
            {
                die('发布失败，uid gid，<a href="index.php?c=admin&a=GroupActivity">点击返回列表</a>');
            }
            foreach($gids as $key=>$gid){
                if(empty($gid)){
                    unset($gids[$key]);
                    continue;
                }
                $gid = $this->redis->hget(REDIS_PREFIX.'GroupInfo_'.$gid, 'gid');
                if(empty($gid)){
                    die('发布失败，gid，<a href="index.php?c=admin&a=GroupActivity">点击返回列表</a>');
                }
            }
            $target = $type == 2? $target2 : $target;
            if(empty($title) || empty($stime) || empty($etime) || empty($introduce) || (($type == 2 || $type==3) && empty($target)) || $stime <= time() || $etime <= $stime){
                die('发布失败，title stime etime introduce type target，<a href="index.php?c=admin&a=GroupActivity">点击返回列表</a>');
            }
            $badwords_mod = $this->load('badwords');
            if($badwords_mod->check($title) || $badwords_mod->check($introduce) || $badwords_mod->check($collect_ext_name1) || $badwords_mod->check($collect_ext_name2))
            {
                die('发布失败，敏感词，<a href="index.php?c=admin&a=GroupActivity">点击返回列表</a>');
            }
            
            $img = $this->load('qiniu')->uploadQiNiuImg('img', 'ACT/'.md5($title.'/'.time().common::getHashStr(6)));
            $img = $img ? $img : $system_img;
            if(empty($img)){
                die('发布失败，<a href="index.php?c=admin&a=GroupActivity">点击返回列表</a>');
            }
            
            foreach($gids as $gid){
                $gInfo = $this->load('group')->getGroupInfo($gid);
                if(empty($gInfo) || $gInfo['isDismiss']){
                    die('发布失败，<a href="index.php?c=admin&a=GroupActivity">点击返回列表</a>');
                }
                $data = compact('uid','gid','title','stime','etime','type','target','img','place','cost','way','introduce','is_show','days','city','lat','lng','address','is_collect_info','collect_ext_name1','collect_ext_name2','limit_member_max');
                $aid = $this->load('groupActivity')->addActivity($data);

                if(empty($aid)){
                    die('发布失败，<a href="index.php?c=admin&a=GroupActivity">点击返回列表</a>');
                }
                if($type == 2 || $type == 4){
                    $this->redis->ZINCRBY(REDIS_PREFIX.'GADay_'.$gid."_".$aid,0,$uid);
                }
                if($type == 1 || $type == 3){
                    $this->redis->ZINCRBY(REDIS_PREFIX.'GARecord_'.$gid."_".$aid,0,$uid);
                }
            }
            
            die('发布成功，<a href="index.php?c=admin&a=GroupActivity">点击返回列表</a>');
        }
    }

    public function dotestTopPostList(){
        $curPage = common::request('p','G',1);
        $type = common::request('t','G',0);
        $hour = common::request('hour','G',12);
        $time = [86400,43200,21600,10800];
        $len = count($time) - 1;
        if($type > $len){
            $type = $len;
        }

        // 计算发帖截止时间
        $days = intval(3);
        $deadLine = time() - 86400 * $days;
        $listRow = 20;
        $offset = ($curPage-1)*$listRow;

        // 获取被屏蔽的帖子
        $extractSql = '';
        $ignorePost = $this->load('bbs')->getHomeBestPostIgnore();
        if($ignorePost)
        {
            $db_create_in = $this->load('push')->db_create_in($ignorePost);
            $extractSql = ' and news_id not '.$db_create_in;
        }
//        $tnum = $this->db->getOne("select count(*) from r_news where is_show = 1".$extractSql." and a_channel = '' and add_time > '{$deadLine}' and board != '[\"0\"]' and board !='[\"groupNews\"]' ");
//        $total = $tnum > 300 ? 300 : $tnum;
//        require FILE . 'lib/page.class.php';
//        $page = new Page($total,$listRow);
//        $pageStr = $page->show();
        $hotPost = $this->db->getAll("select * from r_news where is_show = 1".$extractSql." and a_channel = '' and add_time > '{$deadLine}' and board != '[\"0\"]' and board !='[\"groupNews\"]' limit 300");

        foreach($hotPost as &$item){
            $num = $item['is_home_hot'] * 100 + $item['is_best']*50 + $item['is_top'] * 20 + $item['loves']*50 + $item['total_comment'] * 30 + $item['imgCount']*10;
            $num1 = 0;
            $num > 0 && $num1 = log($num, 10);
            $num = round( $num1 + $item['add_time'] / $time[$type],2);
            $item['nickname'] = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$item['uid'], 'nickname');
            $item['header'] = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$item['uid'], 'header');
            if(common::is_json($item['tag']))
            {
                $tag = json_decode($item['tag'], true);
                if(is_array($tag))
                {
                    foreach ($tag as $key => $tagId) {
                        $tag[$key] = array();
                        $tag[$key]['tagId'] = $tagId;
                        $tag[$key]['tagName'] = $this->redis->hget(REDIS_PREFIX.'TagInfo_'.$tagId, 'tagName');
                    }
                }
                empty($tag) && $tag = array();
            }
            else
            {
                $tag = array();
            }
            $item['tag'] = $tag;
            $board = isset($item['board']) ? json_decode($item['board'], true) : array();
            $temboard = array();
            if(is_array($board) && !empty($board))
            {
                foreach ($board as $key => $boardId) {
                    if(!empty($boardId)){
                        $tem = array();
                        $tem['boardId'] = $boardId;
                        $tem['boardName'] = $this->redis->hget(REDIS_PREFIX.'BoardInfo_'.$boardId, 'boardName');
                        $temboard[] = $tem;
                        unset($tem);
                    }
                }
            }
            $item['board'] = $temboard;
            $weight = ($item['add_time'] - (time() - $hour*3600))/3600;
            $item['weight'] = round($weight);
            $item['hotNum'] = $num;
        }
        uasort($hotPost,array($this,"hotSort"));
        $this->view->assign('hour',$hour);
        $this->view->assign('postList', $hotPost);
        $this->view->display('testpostHotList');
    }

    function hotSort($a,$b){
        return strcmp($b["hotNum"], $a["hotNum"]);
    }

    //活动推荐/取消推荐
    public function doactRecommend(){
        $aid = common::request('id','G');
        $type = common::request('type','G','0');
        $aInfo = $this->load('groupActivity')->getActByAid($aid);
        if($type == 0 && (empty($aInfo) || $aInfo['status'] > 0)){
            $this->_go("该活动不符合推荐规则！");
            exit;
        }
        $redisKey = REDIS_PREFIX."ACTRecommend";
        if($this->redis->zscore($redisKey,$aid) > 0){
            $this->redis->zrem($redisKey,$aid);
        }else{
            $this->redis->zadd($redisKey,$aInfo['addtime'],$aid);
        }
        $this->_go("操作成功！","index.php?c=admin&a=GroupActivity&type=1");

    }

    //活动评论列表
    public function doactComment(){
        $aid = common::request('id',"G");
        $p = common::request("p","G",'1');
        $listRow = 20;
        $num = $this->db->getOne("select count(*) from r_activity_comment where aid = $aid");
        require FILE . 'lib/page.class.php';
        $page = new Page($num,$listRow);
        $offset = ($p-1)*$listRow;
        $pageStr = $page->show();
        $data = $this->db->getAll("select * from r_activity_comment where aid=$aid limit $offset,$listRow");
        foreach($data as &$item){
            $userInfo = $this->load('client')->getUserInfo($item['uid']);
            $item['nickname'] = @$userInfo['nickname'];
            preg_match_all('/(<at href="joggers:\/\/profile\/\d+">.*<\/at>)/U', $item['content'], $matches);
            if(!empty($matches[1]))
            {
                foreach ($matches[1] as $str) {
                    $item['content'] = preg_replace('/<at href="joggers:\/\/profile\/\d+">(.*)<\/at>/U', '@${1} ', $item['content']);
                }
            }
        }
        $this->view->assign('data',$data);
        $this->view->assign('pageStr',$pageStr);
        $this->view->display("actComment");
    }
    
    /*
     * 显示/隐藏活动评论
     */
    public function dohideActComment(){
        $id = common::request('aid','G');
        $cid = common::request('cid','G');
        if(empty($cid)){
            common::tips('参数错误');
        }
        $is_show = common::request('is_show','G') ? '1': '0';
        $data = compact('cid','is_show');
        $this->db->updateRowTable('r_activity_comment',$data);
        echo "修改成功，<a href=\"?c=admin&a=actComment&id={$id}\">点击返回</a>";
        exit;
    }

    //参加官方活动的群组列表
    public function doactGroup(){
        $aid = common::request('id','G');
        $groups = $this->redis->smembers(REDIS_PREFIX."ACTaccept_".$aid);
        $reData = [];
        $totalNum = 0;
        foreach($groups as $k=>$gid){
            $gInfo = $this->load("group")->getGroupInfo($gid);
            $reData[$k]['gid'] = $gInfo['gid'];
            $reData[$k]['name'] = $gInfo['name'];
            $num = $this->load('groupActivity')->joinNum($gid,$aid);
            $reData[$k]['joinNum'] = $num;
            $totalNum += $num;
        }
        $this->view->assign('totalNum',$totalNum);
        $this->view->assign('data',$reData);
        $this->view->assign('aid',$aid);
        $this->view->display("actGroup");
    }

    //添加/回复评论
    public function doaddActComment(){
        if(empty($_POST)){
            $aid = common::request('id',"G");
            $type = common::request('type',"G");
            $fid = common::request("cid","G",0);
            $tid = common::request("uid","G");
            $aInfo = $this->load('groupActivity')->getActByAid($aid);
            if(empty($aInfo)){
                $this->_go("该活动不存在！");
                exit;
            }
            $this->view->assign('aid',$aid);
            $this->view->assign('fid',$fid);
            $this->view->assign('tid',$tid);
            $this->view->assign('type',$type);
            $this->view->display('addActComment');
        }else{
            $uid = intval(common::request('uid',"P"));
            $aid = intval(common::request('aid','P'));
            $tid = intval(common::request('tid','P'));
            $add_time = strtotime(common::request("add_time",'P'));
            $father_id = common::request("fid","P",0);
            $content = common::request('content','P','',true);
            $type = common::request('type','P');
            $url = "?index.php&c=admin&a=GroupActivity&type=$type";
            if($father_id > 0){
                $tUserInfo = $this->load('client')->getUserInfo($tid);
                $content = '回复<at href="joggers://profile/'.$tid.'">'.$tUserInfo['nickname'].'</at>'.$content;
                $url = "?index.php&c=admin&a=actComment&id=$aid";
            }
            $data = compact("uid",'aid','add_time','content',"father_id");
            $id = $this->db->insertRowTable('r_activity_comment',$data);
            if($id > 0){
                $this->_go("操作成功！",$url);
            }else{
                $this->_go("操作失败！");
            }
        }

    }

    /*
     * 群组筛选
     */
    public function dosiftGroup(){
        $members = common::request('members','R');
        $p = common::request('p','R',"1");
        $mileage = common::request('mileage',"R");
        $gid = common::request('gid','R');
        $gname = common::request('gname','R');
        $where = "";
        $fileds = "g.*";
        $param = "";
        $recommendGroup = $this->redis->zrevrange(REDIS_PREFIX.'RecGroupList',0,-1);
        if(!empty($gid)){
            $where .= " and g.gid like '%{$gid}%'";
            $param .= "&gid=$gid";
        }
        if(!empty($gname)){
            $where .= " and g.name like '%{$gname}%'";
            $param .= "&gname=$gname";
        }
        if(!empty($recommendGroup)){
            $gids = implode(",",$recommendGroup);
            $where .= " and g.gid not in($gids)";
        }
        if(!empty($members)){
            $mArr = explode('-',$members);
            $where .= " and members BETWEEN {$mArr[0]} and {$mArr[1]}";
            $param .= "&members=$members";
        }
        if(!empty($mileage)){
            if(strpos($mileage,'-') !== false){
                $m = explode("-",$mileage);
                $where .= " group by gr.gid having s >= {$m[0]} and s <= {$m[1]} order by s desc";
            }else{
                $where .= " group by gr.gid having s >= $mileage order by s desc";
            }
            $param .= "&mileage=$mileage";
            $fileds .= ",sum(mileage) s";
        }else{
            $where .= " group by g.gid";
        }
        $datas = $this->db->getAll("select $fileds from r_group g left join r_group_run gr on g.gid=gr.gid where isDismiss=0 $where ");
        $num = count($datas);
        require FILE . 'lib/page.class.php';
        $listRow = 20;
        $page = new Page($num,$listRow,$param);
        $offset = ($p-1)*$listRow;
        $pageStr = $page->show();
        $groupList = $this->db->getAll("select $fileds from r_group g left join r_group_run gr on g.gid=gr.gid where isDismiss=0  $where limit $offset,$listRow");
        foreach($groupList as &$v){
            $v['mileage'] = floatval($this->redis->hget(REDIS_PREFIX.'GRTotal',$v['gid']));
        }
        $this->view->assign('groupList', $groupList);
        $this->view->assign('members', $members);
        $this->view->assign('mileage', $mileage);
        $this->view->assign('pageStr', $pageStr);
        $this->view->display('siftGroup');
    }

    /**
     * 活动评论列表
     */
    public function dorecommendActList(){
        $actIds = $this->redis->zrevRange(REDIS_PREFIX."ACTRecommend",0,-1);
        $list = [];
        foreach($actIds as $item){
            $actInfo = $this->load('groupActivity')->getActByAid($item);
            $userInfo = $this->load('client')->getUserInfo($actInfo['uid']);
            $actInfo['name'] = @$userInfo['name'];
            
            if(empty($actInfo['gid'])){
                $gids = $this->redis->sMembers(REDIS_PREFIX."ACTaccept_".$actInfo['aid']);
                $num = 0;
                foreach($gids as $gid){
                    $num += $this->load('groupActivity')->joinNum($gid,$actInfo['aid']);
                }
            }else{
                $num = $this->load('groupActivity')->joinNum($actInfo['gid'],$actInfo['aid']);
            }
            $actInfo['joinNum'] = $num;
            $list[] = $actInfo;
        }
        $type = array("自定义活动","目标里程","目标打卡","官方目标","官方打卡","官方自定义");
        $status = array("正常","已取消","已结束");
        $this->view->assign("type",$type);
        $this->view->assign("status",$status);
        $this->view->assign("list",$list);
        $this->view->display('recommendActList');
    }

    /**
     * 某群群组活动列表
     */
    public function dogroupActList(){
        $gid = common::request('gid',"G",0);
        $p = common::request("p",'G',1);
        $num = $this->db->getOne("select count(*) from r_group_activity where status != 1 and gid=$gid");
        require FILE . 'lib/page.class.php';
        $listRow = 20;
        $page = new Page($num,$listRow);
        $offset = ($p-1)*$listRow;
        $pageStr = $page->show();
        $data = $this->db->getAll("select * from r_group_activity where status != 1 and gid=$gid order by addtime desc limit $offset,$listRow");
        $type = array("自定义活动","目标里程","目标打卡","官方目标","官方打卡","官方自定义");
        $status = array("正常","已取消","已结束");
        $this->view->assign('type',$type);
        $this->view->assign('status',$status);
        $this->view->assign('list',$data);
        $this->view->assign('pageStr',$pageStr);
        $this->view->display("groupActList");
    }

    /**
     * js页面跳转
     * @param $message
     * @param string $url
     */
    private function _go($message,$url=''){
        common::tips($message,$url);
    }
    
    /*
     * 有道统计
     */
    public function donewsReport(){
        $endTime = time();
        $startTime = $endTime - 6*24*3600;
        
        $reporta = common::request('reporta','G','post');
        $startTimeStr = common::request('startTimeStr','P','');
        $endTimeStr = common::request('endTimeStr','P','');
        $search = compact('reporta','startTimeStr','endTimeStr');
        
        $startTimeStr && $startTime = strtotime($startTimeStr);
        $endTimeStr && $endTime = strtotime($endTimeStr);
        
        $this->in_logDb();
        $sql = "SELECT * FROM d_api_count WHERE a = '$reporta' AND add_time BETWEEN $startTime AND $endTime";
        $rows = $this->logDb->getAll($sql);

        $xAxis = [];
        $series = [];
        $tags = [
            'hotans'=>'每日热答',
            'showtime'=>'showtime',
            'rungear'=>'跑步装备',
            'injury'=>'损伤保护',
            'beginner'=>'新手入门',
            'healthy'=>'减肥健身',
            'runmood'=>'跑步心情',
            'events'=>'跑天下',
            'training'=>'提高训练',
            'marathon'=>'马拉松',
            'news'=>'1.0资讯',
            '0'=>'1.0资讯',
            'groupNews'=>'空间帖子',
            'all'=>'所有'
        ];
        $search_arr = array_keys($tags);
        $replace_arr = array_values($tags);
        foreach($rows as $row){
            $date = date('Y-m-d',$row['add_time']);
            $values = json_decode($row['value'],true);
            if(!in_array($date,$xAxis)){
                $xAxis[] = $date;
            }

            //$series = [ tag => [date1=>value,date2=>value] ]
            if(!empty($values)){
                foreach($values as $k=>$v){
                    $k = str_replace(['["','"]','","'],'',$k);
                    //$tag = isset($tags[$k]) ? $tags[$k] : $k;
                    $tag = str_replace($search_arr,$replace_arr,$k);
                    if(isset($series[$tag][$date])){
                        $series[$tag][$date] += $v;
                    }else{
                        $series[$tag][$date] = $v;
                    }
                }
            }
        }
        
        $titles = [
            'postData' => '点击数',
            'postData_user' => '点击人数',
            'getCommentList' => '点击数2',
            'getCommentList_user' => '点击人数2',
            'post' => '发帖数',
            'post_user' => '发帖人数',
            'publishComment' => '回复数',
            'publishComment_user' => '回复人数',
            'likePost' => '点赞数',
            'likePost_user' => '点赞人数',
            'upComment' => '点亮数',
            'upComment_user' => '点亮人数'
        ];
        
        $data = [
            'title' => ['text'=>'有道'.$titles[$reporta]],
            'subtitle' => ['text'=>''],
            'xAxis' => ['categories'=>$xAxis],
            'yAxis' => ['title'=>['text'=>$titles[$reporta]]],
        ];
        $data['tooltip']['valueSuffix'] = strpos($reporta,'_user') ? '人' : '次';
        
        foreach($series as $k=>$v){
            foreach($xAxis as $date){
                !isset($v[$date]) && $v[$date] = 0;
            }
            $data['series'][] = ['name'=>$k,'data'=>array_values($v)];
        }
        
        $this->view->assign('title',$titles[$reporta]);
        $this->view->assign('dates',$xAxis);
        $this->view->assign('series',$series);
        $this->view->assign('data', json_encode($data));
        $this->view->assign('search',$search);
        $this->view->display('newsReport');
    }
    
    public function doweatherReport(){
        $endTimeStr = common::request('endTimeStr','R');
        $_weather = common::request('weather','G');
        $weatherName = common::request('weatherName','G');
        $search = compact('endTimeStr');
        
        $endTime = $endTimeStr ? strtotime($endTimeStr) : time();
        $startTime = strtotime(date('Y-m-d 00:00:00',$endTime));
        $yesterdayEndTime = $endTime - 24*3600;
        $yesterdayStartTime = $startTime -24*3600;
        
        $log_mod = $this->load('log');
        $todayReport = $log_mod->getWeatherReport($startTime,$endTime);
        $yesterdayReport = $log_mod->getWeatherReport($yesterdayStartTime,$yesterdayEndTime);
        
        $runningData_sum = ['weather_city'=>0,'temperature_city'=>0,'pm25_city'=>0];
        $yesterdaySum = 0;
        foreach($todayReport as $weather=>&$values){
            foreach($values as $name=>&$val){
                foreach($val as $tag=>&$v){
                    if($tag == 'runningData_city'){
                        $runningData_sum[$weather] += $v;
                    }
                    if($tag != 'cities'){
                        $v = [
                            'value'=>$v,
                            'thread'=>isset($yesterdayReport[$weather][$name][$tag]) ? number_format(($v - $yesterdayReport[$weather][$name][$tag])*100/$yesterdayReport[$weather][$name][$tag],2) : 100
                        ];
                    }
                }
                if(empty($val['register_city'])){
                    $val['register_city'] = [
                        'value' => 0,
                        'thread' => -100,
                    ];
                }
                if(empty($val['runningData_city'])){
                    $val['runningData_city'] = [
                        'value' => 0,
                        'thread' => -100,
                    ];
                }
                ksort($val);
            }
        }
        
        $titles = [
            'register_city'=>'注册',
            'runningData_city'=>'跑步',
        ];
        
        $this->view->assign('search',$search);
        $this->view->assign('titles',$titles);
        $this->view->assign('runningData_sum',$runningData_sum);
        
        if($_weather && $weatherName){
            $this->view->assign('_weather',$_weather);
            $this->view->assign('weatherName',$weatherName);
            $this->view->assign('todayReport',$todayReport[$_weather]);
            //$this->view->assign('yesterdayReport',$yesterdayReport[$weather]);
            $this->view->display('weatherReportDetail');
        }else{
            $this->view->assign('todayReport',$todayReport);
            //$this->view->assign('yesterdayReport',$yesterdayReport);
            $this->view->display('weatherReport');
        }
    }
    
    public function docitiesReport(){
        $log_mod = $this->load('log');
        $endTime = strtotime(date('Y-m-d 00:00:00',time()));
        $startTime = $endTime - 24*3600;
        $yesterdayReport = $log_mod->getWeatherReport($startTime,$endTime);
        $yesterdayReport1 = $yesterdayReport['cities'];
        
        $endTime = $startTime;
        $startTime = $endTime - 24*3600;
        $dayBeforeYesterdayReport = $log_mod->getWeatherReport($startTime,$endTime);
        $dayBeforeYesterdayReport = $dayBeforeYesterdayReport['cities'];
        
        $yesterdayReport = [];
        foreach($yesterdayReport1 as $city => $v){
            $v['city'] = $city;
            $old_runningData = $dayBeforeYesterdayReport[$city]['runningData_city'];
            $v['old_runningData_city'] = $old_runningData;
            $v['runningData_thread'] = number_format(($v['runningData_city'] - $old_runningData)*100/$old_runningData);
            $yesterdayReport[$v['runningData_city']] = $v;
        }
        
        krsort($yesterdayReport);
        $yesterdayReport = array_slice($yesterdayReport,0,50,false);
        
        $this->view->assign('yesterdayReport',$yesterdayReport);
        //$this->view->assign('dayBeforeYesterdayReport',$dayBeforeYesterdayReport);
        $this->view->display('citiesReport');
    }
    
    public function docityReport(){
        $city = common::request('city','R','上海');
        $endTimeStr = common::request('endTimeStr','R');
        $endTime = $endTimeStr ? strtotime($endTimeStr) : time();
        $startTime = $endTime - 6*24*3600;
        $search = compact('endTimeStr','city');
        
        $this->in_logDb();
        $sql = "SELECT * FROM d_api_count WHERE a IN('register_city','runningData_city') AND add_time BETWEEN $startTime AND $endTime";

        $rows = $this->logDb->getAll($sql);
        
        $titles = [
            'register_city'=>'注册',
            'runningData_city'=>'跑步',
        ];
        $xAxis = [];
        $series = [];
        foreach($rows as $row){
            $date = date('Y-m-d',$row['add_time']);
            $tag = $titles[$row['a']];
            $values = json_decode($row['value']);
            if(!in_array($date,$xAxis)){
                $xAxis[] = $date;
            }
            
            foreach($values as $_city=>$value){
                if($_city != $city){
                    continue;
                }
                if(isset($series[$tag][$date])){
                    $series[$tag][$date] += $value;
                }else{
                    $series[$tag][$date] = $value;
                }
            }
        }
        
        $data = [
            'title' => ['title'=>$city],
            'subtitle' => ['text'=>''],
            'xAxis' => ['categories'=>$xAxis],
            'yAxis' => ['title'=>['text'=>'数据']],
            'tooltip' =>['valueSuffix'=>'人']
        ];
        
        foreach($series as $k=>$v){
            foreach($xAxis as $date){
                !isset($v[$date]) && $v[$date] = 0;
            }
            $v = $this->load('log')->getMarkedLine($v);
            $data['series'][] = ['name'=>$k,'data'=>array_values($v)];
        }

        //获取天气相关信息
        $weatherSql = "SELECT city, FROM_UNIXTIME(addtime, '%Y-%m-%d') addTime, weather, temperature, pm25 FROM r_log_weather WHERE city = \"{$city}\" and addtime BETWEEN $startTime AND $endTime";
        $weatherData = $this->logDb->getAll($weatherSql);
        //合并数据
        $series['天气'] = '';
        $series['温度'] = '';
        $series['PM2.5'] = '';
        $weather_Str = '';
        $temperature_Str = '';
        $pm25_Str = '';
        foreach ($series['注册'] as $key => $value) {
            $weather_arr = [];
            $temperature_arr = [];
            $pm25_arr = [];
            foreach ($weatherData as &$weather) {
                if($key == $weather['addTime']){
                    $weather_arr[] = $weather['weather'];
                    $temperature_arr[] = $weather['temperature'];
                    $pm25_arr[] = $weather['pm25'];
                }
            }
            $temperature_arr = array_unique($temperature_arr);
            $pm25_arr = array_unique($pm25_arr);
            $temperature_Str = $temperature_arr[0];
            if(count($temperature_arr) > 1){
                $temperature_Str = min($temperature_arr).'~'.max($temperature_arr);
            }
            $pm25_Str = $pm25_arr[0];
            if(count($pm25_arr) > 1){
                $pm25_Str = min($pm25_arr).'~'.max($pm25_arr);
            }
            $series['天气'][$key] = implode(',',array_unique($weather_arr));
            $series['温度'][$key] = $temperature_Str;
            $series['PM2.5'][$key] = $pm25_Str;
        }

        $this->view->assign('titles',$titles);
        $this->view->assign('dates',$xAxis);
        $this->view->assign('series',$series);
        $this->view->assign('data', json_encode($data));
        $this->view->assign('search',$search);
        $this->view->display('cityReport');
    }
    
    public function doconcernGroupsReport(){
        $endTimeStr = common::request('endTimeStr','R');
        $search = compact('endTimeStr');
        
        $endTime = $endTimeStr ? strtotime($endTimeStr) : time();
        
        $titles = [
            'createActivity_group' => '活动',
            'runningData_group' => '跑步',
            'post_group' => '发帖',
            'quit_group' => '退群',
            'applyGroup_group' => '加群'
        ];
        //$this->view->assign('titles',$titles);
        $this->view->assign('search',$search);
        
        $startTime = strtotime(date('Y-m-d 00:00:00',$endTime));
        $yesterdayEndTime = $endTime - 24*3600;
        $yesterdayStartTime = $startTime - 24*3600;
        
        $log_mod = $this->load('log');
        $todayReport = $log_mod->getConcernGroupsReport($startTime,$endTime);
        $yesterdayReport = $log_mod->getConcernGroupsReport($yesterdayStartTime,$yesterdayEndTime);
        
        $titles = [];
        $group_mod = $this->load('group');
        foreach($todayReport as $gid=>&$values){
            $group_info = $group_mod->getGroupInfo($gid);
            foreach($values as $tag=>&$v){
                $titles[] = $tag;
                $v = [
                    'value'=>$v,
                    'thread'=>isset($yesterdayReport[$gid][$tag]) ? ($v - $yesterdayReport[$gid][$tag])/$yesterdayReport[$gid][$tag] : 0
                ];
            }
            $values['name'] = $group_info['name'];
            $titles[] = '名称';
            $values['city'] = $group_info['city'];
            $titles[] = '城市';
        }
        
        $this->view->assign('titles',$titles);
        $this->view->assign('todayReport',$todayReport);
        $this->view->display('concernGroupsReport');
    
    }
    
    public function doconcernGroupReportDetail(){
        $gid = common::request('gid','R');
        $endTimeStr = common::request('endTimeStr','R');
        $search = compact('gid','endTimeStr');
        
        $endTime = $endTimeStr ? strtotime($endTimeStr) : time();
        
        $titles = [
            'createActivity_group' => '活动',
            'runningData_group' => '跑步',
            'post_group' => '发帖',
            'quit_group' => '退群',
            'applyGroup_group' => '加群'
        ];
        $this->view->assign('titles',$titles);
        $this->view->assign('search',$search);
        
        $startTime = $gid ? $endTime - 7*24*3600 : $endTime - 24*3600;
        $this->in_logDb();
        $as_str = implode("','",array_keys($titles));
        $sql = "SELECT * FROM d_api_count WHERE a IN('$as_str') AND add_time BETWEEN $startTime AND $endTime";
        $rows = $this->logDb->getAll($sql);
        
        $xAxis = [];
        $series = [];
        foreach($rows as $row){
            $date = date('Y-m-d',$row['add_time']);
            $values = json_decode($row['value'],true);
            if(!isset($values[$gid])){
                continue;
            }
            if(!in_array($date,$xAxis)){
                $xAxis[] = $date;
            }
            
            $tag = $titles[$row['a']];
            if(isset($series[$tag][$date])){
                $series[$tag][$date] += $values[$gid];
            }else{
                $series[$tag][$date] = $values[$gid];
            }
        }
        
        $data = [
            'title' => ['title'=>'群组一周统计'],
            'subtitle' => ['text'=>''],
            'xAxis' => ['categories'=>$xAxis],
            'yAxis' => ['title'=>['text'=>'统计值']],
            'tooltip' => ['valueSuffix' => '次']
        ];
        foreach($series as $k=>$v){
            foreach($xAxis as $date){
                !isset($v[$date]) && $v[$date] = 0;
            }
            $v = $this->load('log')->getMarkedLine($v);
            $data['series'][] = ['name'=>$k,'data'=>array_values($v)];
        }
        
        $this->view->assign('dates',$xAxis);
        $this->view->assign('series',$series);
        $this->view->assign('data',json_encode($data));
        $this->view->display('concernGroupReport');
    }
    
    public function docommonReport(){
        $endTime = time();
        //$startTime = $endTime - 3*24*3600;
        
        $actionGroups = [
            'groupA' => [
                'title'=>'群组统计',
                'as' => ['createGroup','dismiss','applyGroup','quit'],
                'tags' => ['createGroup'=>'新增群组','dismiss'=>'解散群组','applyGroup'=>'加入群组','quit'=>'退出群组'],
                'startTime' => $endTime - 7*24*3600
            ],
            'groupB' => [
                'title'=>'群组跑步记录统计',
                'as' => ['groupRun'],
                'tags' => ['nomal'=>'群组跑步记录','nomal_user'=>'有记录用户数','is_delete'=>'删除跑步记录','is_delete_user'=>'删记录用户数','overSpeed'=>'异常记录','overSpeed_user'=>'异常记录用户数'],
                'startTime' => $endTime - 7*24*3600
            ],
            'groupC' => [
                'title' => '群组各状态活动',
                'as' => ['createActivity','handleActivity','search'],
                'tags' => ['createActivity'=>'创建活动','s0'=>'未开始活动','s1'=>'进行中活动','s2'=>'已结束活动','join'=>'加入活动','quit'=>'退出活动','cancel'=>'取消活动','search'=>'搜索活动'],
                'startTime' => $endTime - 7*24*3600
            ],
            'userA' => [
                'title' => '用户统计-渠道',
                'as' => ['register_android','register_ios','login_android','login_ios','visitor_android','visitor_ios'],
                'tags' => ['register_android'=>'安卓注册','register_ios'=>'苹果注册','login_android'=>'安卓登录','login_ios'=>'苹果登录','visitor_android'=>'安卓访客','visitor_ios'=>'ios访客'],
                'startTime' => $endTime-7*24*3600
            ],
            'userB' => [
                'title' => '用户统计-版本（r开头表示注册，l开头表示登录）',
                'as' => ['register','login','visitor'],
                'tags' => ['register_all'=>'所有注册','login_all'=>'所有登录'],
                'startTime' => $endTime - 7*24*3600
            ],
            'userC' => [
                'title' => '绑定方式',
                'as' => ['bindSocialUser','bindPhone'],
                'tags' => ['c2' => 'qq','c3' => 'sina','c4' => 'weixin','c5' => 'renren','c6' => 'phone','all'=>'所有','bindPhone'=>'绑定手机'],
                'startTime' => $endTime - 7*24*3600
            ],
            'userD' => [
                'title' => '空间访问',
                'as' => ['getUserCenterInfo'],
                'tags' => ['other'=>'访问他人','all'=>'访问总数'],
                'startTime' => $endTime -7*24*3600
            ],
            'runnningA' => [
                'title' => '跑步记录',
                'as' => ['runningData','runningData_overSpeed','DelRunningData','delRunData'],
                'tags' => ['runningData'=>'新增跑步记录','runningData_overSpeed'=>'异常记录','DelRunningData'=>'用户删除跑步记录','delRunData'=>'客户删除跑步记录'],
                'startTime' => $endTime - 7*24*3600
            ],
            'runningB' => [
                'title' => '7天内跑步记录',
                'as' => ['runningData_user'],
                'tags' => ['once' => '7天内跑一次','twice' => '7天内跑两次','more' => '7天内跑两次以上','twice_consecutive' => '7天内连续跑两次','more_consecutive' => '7天内连续跑两次以上'],
                'startTime' => $endTime -7*24*3600
            ],
            'client' => [
                'title' => '客户端活跃数据',
                'as' => ['new_client','active_client'],
                'tags' => ['new_client_android'=>'安卓新增客户端','new_client_ios'=>'ios新增客户端','active_client_android'=>'安卓活跃客户端','active_client_ios'=>'ios活跃客户端'],
                'startTime' => $endTime -3*24*3600
            ],
            'im' => [
                'title' => 'IM用户统计',
                'as' => ['im'],
                'tags' => ['uid_count'=>'发消息人数','message_count'=>'用户消息总数','push_count'=>'分发消息数'],
                'startTime' => $endTime -3*24*3600
            ]
    
        ];
        $reporta = common::request('reporta','G','groupA');
        $reporta = $actionGroups[$reporta];
        extract($reporta);
        
        $startTimeStr = common::request('startTimeStr','P','');
        $endTimeStr = common::request('endTimeStr','P','');
        $search = compact('startTimeStr','endTimeStr');
        
        $startTimeStr && $startTime = strtotime($startTimeStr);
        $endTimeStr && $endTime = strtotime($endTimeStr);
        
        $this->in_logDb();
        $as = implode("','",$as);
        $sql = "SELECT * FROM d_api_count WHERE a IN('$as') AND add_time BETWEEN $startTime AND $endTime";
        $rows = $this->logDb->getAll($sql);
        
        $xAxis = [];
        $series = [];
        foreach($rows as $row){
            $date = date('Y-m-d',$row['add_time']);
            if(!in_array($date,$xAxis)){
                $xAxis[] = $date;
            }
            
            if(!is_numeric($row['value'])){
                $values = json_decode($row['value'],true);
                foreach($values as $k=>$v){
                    $tag = isset($tags[$k]) ? $tags[$k] : $k;
                    if(isset($series[$tag][$date])){
                        $series[$tag][$date] += (int)$v;
                    }else{
                        $series[$tag][$date] = (int)$v;
                    }
                }
            }else{
                $tag = $tags[$row['a']];
                if(isset($series[$tag][$date])){
                    $series[$tag][$date] += (int)$row['value'];
                }else{
                    $series[$tag][$date] = (int)$row['value'];
                }
            }
        }
        
        $data = [
            'title' => ['text'=>$title],
            'subtitle' => ['text'=>''],
            'xAxis' => ['categories'=>$xAxis],
            'yAxis' => ['title'=>['text'=>$title]],
            'tooltip' => ['valueSuffix'=>'次']
        ];
        
        foreach($series as $k=>$v){
            foreach($xAxis as $date){
                !isset($v[$date]) && $v[$date] = 0;
            }
            ksort($v);
            $data['series'][] = ['name'=>$k,'data'=>array_values($v)];
        }
        
        $this->view->assign('title',$title);
        $this->view->assign('dates',$xAxis);
        $this->view->assign('series',$series);
        $this->view->assign('data', json_encode($data));
        $this->view->assign('search',$search);
        $this->view->display('commonReport');
    }
    
    /*
     * 运营记录
     */
    public function doadminRemark(){
        $startTimeStr3 = common::request("startTimeStr2",'P');
        $remark = common::request("remark",'P');
        $deleteId = common::request("deleteId","G");
        //插入
        if($startTimeStr3 && $remark){
            $data = [
                'starttime'=>strtotime($startTimeStr3),
                'remark'=>$remark,
                'addtime'=>time()
            ];
            $this->db->insertRowTable('r_admin_remark',$data);
        }
        //删除
        elseif($deleteId){
            $this->db->delDataTable('r_admin_remark',"id=$deleteId limit 1");
        }
        
        //展示
        $startTimeStr = common::request("startTimeStr",'P');
        $endTimeStr = common::request("endTimeStr",'P');
        $search = compact('startTimeStr','endTimeStr');
        
        $endTime = $startTimeStr ? strtotime($startTimeStr) : time();
        $startTime = $endTimeStr ? strtotime($endTimeStr) : $endTime - 30*24*3600;
        $sql = "SELECT * FROM r_admin_remark WHERE starttime BETWEEN $startTime AND $endTime";
        $adminRemark = $this->db->getAll($sql);
        
        $this->view->assign('search',$search);
        $this->view->assign('adminRemark',$adminRemark);
        $this->view->display('adminRemark');
    }
    
    /*
     * 关注的群
     */
    public function doconcernGroup(){
        $gid = common::request("gid",'P');
        $remark = common::request("remark",'P');
        $deleteId = common::request("deleteId","G");
        //插入
        if($gid && $remark){
            $addtime = time();
            $this->db->insertRowTable('r_admin_concern_group',compact('gid','remark','addtime'));
        }
        //删除
        elseif($deleteId){
            $this->db->delDataTable('r_admin_concern_group',"id=$deleteId limit 1");
        }
        
        //展示
        $sql = "SELECT * FROM r_admin_concern_group";
        $concernGroup = $this->db->getAll($sql);
        
        $this->view->assign('concernGroup',$concernGroup);
        $this->view->display('concernGroup');
    }
    
    /**
     *  统计群组人均跑量以及某段时间的总跑量
     */
    public function dogroupStatics(){
        $stime = common::request("stime","R");
        $etime = common::request("etime","R");
        $gids = common::request("gids","R");
        $p = common::request("p","G",1);
        if(empty($stime)){
            $stime = strtotime("-3 day");
        }else{
            $stime = strtotime($stime);
        }
        if(empty($etime)){
            $etime = time();
        }else{
            $etime = strtotime($etime);
        }
        $s = date("Y-m-d H:i:s",$stime);
        $e = date("Y-m-d H:i:s",$etime);
        $param = "&stime={$s}&etime={$e}";
        require FILE . 'lib/page.class.php';
        $listRow = 20;
        $num = $this->db->getOne("select count(*) from (select gid from r_group_run where updatetime>='{$stime}' and updatetime <='{$etime}' group by gid) t");
        if(!empty($gids)){
            $gids  = str_replace("，",",",$gids);
            $gidArr = explode(",",$gids);
            $num = count($gidArr);
            $listRow = $num;
        }
        $page = new Page($num,$listRow,$param);
        $offset = ($p-1)*$listRow;
        $pageStr = $page->show();
        if(!empty($gids)){
            $data = $this->db->getAll("select gid,sum(mileage) s from r_group_run where updatetime>='{$stime}' and updatetime <='{$etime}' and is_delete=0 and gid in({$gids})");
            foreach($gidArr as $k=>$gid){
                $s = $this->db->getOne("select sum(mileage) from r_group_run where is_delete=0 and updatetime>='$stime' and updatetime <='$etime' and gid=$gid");
                $data[$k]['s'] = $s;
                $data[$k]['gid'] = $gid;
                $st = $this->db->getRow("select sum(s) sum,count(*) total from(select sum(mileage) s from r_group_run where gid=$gid and updatetime>=$stime and updatetime <= $etime and is_delete=0 group by uid order by s desc limit 10) t");
                $data[$k]['topAvg'] = empty($st) ? 0 : round(($st['sum']/$st['total']),2);
            }
        }else{
            $data = $this->db->getAll("select gid,sum(mileage) s from r_group_run where updatetime>='{$stime}' and updatetime <='{$etime}' and is_delete=0 group by gid order by s desc limit $offset,$listRow");
        }
        foreach($data as $k=>&$info){
            $groupInfo = $this->load('group')->getGroupInfo($info['gid']);
            if(!empty($groupInfo)){
                $runNum = $this->db->getOne("select count(*) from (select uid from r_group_run where gid={$info['gid']} and updatetime>='{$stime}' and updatetime <='{$etime}' and is_delete=0 group by uid) t");

                $info['name'] = $groupInfo['name'];
                $info['runNum'] = $runNum;
                $info['members'] = $groupInfo['members'];
                $info['avg'] = $runNum > 0 ? round($info['s']/$runNum,2) : 0;
                $st = $this->db->getRow("select sum(s) sum,count(*) total from(select sum(mileage) s from r_group_run where gid={$info['gid']} and updatetime>=$stime and updatetime <= $etime and is_delete=0 group by uid order by s desc limit 10) t");
                $data[$k]['topAvg'] = empty($st) ? 0: round(($st['sum']/$st['total']),2);

                $info['activityCount'] = $this->db->getOne("select count(1) from r_group_activity where gid = {$info['gid']}");
                $ac = $this->redis->zcard(REDIS_PREFIX . 'GroupActivity_' . $info['gid']);
                $info['officeActivityCount'] = isset($ac) ? $ac - $info['activityCount'] : 0;

            }else{
                unset($data[$k]);
            }
        }
        $this->view->assign('groupList',$data);
        $this->view->assign('stime',$stime);
        $this->view->assign('etime',$etime);
        $this->view->assign('groupList',$data);
        $this->view->assign('pageStr',$pageStr);
        $this->view->display("groupStatics");



    }

    /**
     * 勋章补发
     */
    public function dodealMedal(){
        $uid = common::request('uid','R');
        $did = common::request('did','R');
        $medal_id = common::request("medal_id",'R');
        $second = intval(common::request('second', 'P'));

        if($medal_id && $uid){
            $res = null;
            $medal_mod = $this->load('medal');
            $uids = explode(';',$uid);
            $medalInfo = $this->load('medal')->getMedalInfo($medal_id);
            if(empty($medalInfo)){
                $this->_go("不存在该勋章！");
                return ;
            }
            if($did && count($uids)==1){
                $uid = $uids[0];
                $runData = $this->db->getRow("select uid,medal,updatetime from r_data where did='$did' and is_delete=0");
                if(empty($runData)){
                    $this->_go("此跑步记录不存在！");
                    return ;
                }
                $medal = json_decode($runData['medal'],true);
                $medal[] = $medal_id;
                $medal = json_encode($medal);

                // 记录型勋章对应数据更新
                if($second && in_array($medal_id, [126, 127, 128, 129]))
                {
                    switch($medal_id)
                    {
                        case 126:
                            $item = 'five_time';
                            break;
                        case 127:
                            $item = 'ten_time';
                            break;
                        case 128:
                            $item = 'half_mtime';
                            break;
                        case 129:
                            $item = 'mara_time';
                            break;
                    }

                    $this->db->update("update r_data set {$item}={$second} where did='{$did}'");
                    $this->load('client')->setUserInfo($uid, ['max_' . $item => $second]);
                }
                $res = $medal_mod->addUserMedal($uid,$medal_id,date("Ymd",$runData['updatetime']));
                $this->db->query("update r_data set medal='$medal' where did='$did'");
                $url = "?c=admin&a=showHistory&uid=$uid&t=1";
            }else{
                $nowStr = date('Ymd',time());
                foreach($uids as $_uid){
                    if(!$_uid || !is_numeric($_uid) || !$medal_mod->checkCanGetMedal($_uid,$medal_id)){
                        continue;
                    }
                    
                    $res = $medal_mod->addUserMedal($_uid,$medal_id,$nowStr);
                }
                $url = "?c=admin&a=medalList";
            }
            
            if($res){
                $this->_go("添加成功！",$url);
            }else{
                $this->_go("添加失败！",$url);
            }
            exit;
        }
        
        $medals = $this->db->getAll("select medal_id,medal_name from r_medal");

        //勋章已发数量
        $number = 0;
        if($medal_id){
            $number = $this->db->getOne("select sum(number) number from r_medal_record where medal_id = {$medal_id}");
        }
        $this->view->assign('uid',$uid);
        $this->view->assign('did',$did);
        $this->view->assign('medal_id',$medal_id);
        $this->view->assign('number',$number);
        $this->view->assign('medals',$medals);
        $this->view->display("addMedal");

    }

    /**
     * 群组跑步总里程前十用户
     */
    public function dogroupTOP(){
        $gid = common::request('gid',"G");
        $stime = common::request('stime',"G");
        $etime = common::request('etime',"G");
        $data = $this->db->getAll("select uid,sum(mileage) s from r_group_run where gid=$gid and updatetime>=$stime and updatetime <= $etime and is_delete=0 group by uid order by s desc limit 10");
        foreach($data as &$info){
            $userInfo = $this->load('client')->getUserInfo($info['uid']);
            $groupInfo = $this->load('group')->getGroupInfo($gid);
            $info['nickname'] = $userInfo['nickname'];
            $info['name'] = $groupInfo['name'];
            $info['gid'] = $gid;
        }
        $this->view->assign('stime',$stime);
        $this->view->assign('etime',$etime);
        $this->view->assign('list',$data);
        $this->view->display('groupTop');
    }
    
    /*
     * 赛事列表
     */
    public function domatchList(){
        $p = common::request('p','R',1);
        
        //分页
        require FILE . 'lib/page.class.php';
        $listNum = 20;
        $start = ($p - 1)*$listNum;
        $sql = "SELECT count(*) FROM r_match";
        $num = $this->db->getOne($sql);
        $page = new Page($num, $listNum);
        $this->view->assign('pageStr',$page->show());
        
        $sql = "SELECT match_id,name,stime,etime,user_count,group_count,status,match_type FROM r_match ORDER BY match_id DESC LIMIT $start,$listNum";
        $matchList = $this->db->getAll($sql);
        
        $now = time();
        foreach($matchList as &$match){
            if($match['status']==1 && $match['stime']<=$now && $now<=$match['etime']){
                $match['status'] = 2;
            }elseif($match['status']==1 && $match['etime']<$now){
                $match['status'] = 3;
            }
        }
        
        $this->view->assign('matchStatus',common::$matchStatus);
        $this->view->assign('matchList',$matchList);
        $this->view->display('matchList');
    }
    
    /*
     * 赛事详情
     */
    public function domatchInfo(){
        $type = common::request('type','G','create');
        $match_id = common::request('match_id','R');
        $introduce = '';
        $add_introduce = '';
         
        if($match_id){                         
            $matchInfo = $this->load('match')->getMatchInfo($match_id);
            $matchInfo['stime'] = date('Y-m-d H:i:s',$matchInfo['stime']);
            $matchInfo['etime'] = date('Y-m-d H:i:s',$matchInfo['etime']);
            $introduce = $matchInfo['introduce'];
            $matchInfo['introduce'] = '';
            $add_introduce = $matchInfo['add_introduce'];
            $matchInfo['add_introduce'] = '';
            unset($matchInfo['goods']);
            if($matchInfo['fee_goods_id']){
                $fee_goods = $this->load('goods')->getRaceGoodsInfo($matchInfo['fee_goods_id']);
                $matchInfo['cost'] = $fee_goods['goodsInfo']['saleprice'];
            }else{
                $matchInfo['cost'] = '0.00';
            }
        }else{
            $matchInfo = [
                'name'=>'',
                'stime'=>'',
                'etime'=>'',
                'match_type'=>0,
                'user_count'=>0,
                'group_count'=>0,
                'aim_desc'=>'',
                'rule'=>[
                        'user_rule'=>[],
                        'group_rule'=>[]
                    ],
                'template_id'=>0,
                'introduce'=>'',
                'introduce_url'=>'',
                'introduce_type'=>0,
                'banner_src'=>'',
                'logo_src'=>'',
                'sponsor'=>'',
                'user_tabs'=>[],
                'group_tabs'=>[],
                'menu_items'=>[],
                'limit_member_max'=>'0',
                'cost'=>'0.00',
                'fee_goods_id'=>'0',
                'is_free_add'=>'0',
                'status'=>0,
                'discount'=>[],
                'add_introduce'=>''
            ];
        }
        
        $this->view->assign('zuokuohao','{{');
        $this->view->assign('youkuohao','}}');
        $this->view->assign('introduce',$introduce);
        $this->view->assign('add_introduce',$add_introduce);
        $this->view->assign('matchInfoJSON',json_encode($matchInfo));
        $this->view->assign('matchStatus',json_encode(common::$matchStatus));
        $this->view->display('matchInfo');
    }
    
    /*
     * 添加或修改赛事
     */
    public function domatchAction(){
        $matchInfo = json_decode(common::request('matchInfoJSON','P'),true);
        $matchInfo['stime'] = common::request('stime','P');
        $matchInfo['etime'] = common::request('etime','P');
        $matchInfo['introduce'] = common::request('introduce','P','');
        $matchInfo['add_introduce'] = common::request('add_introduce','P','');
        $time = time();
        
        //图片
        $this->load('qiniu');
        $imgName = $time.common::getHashStr();
        $imgSrc = $_ENV['qiniu']->uploadQiNiuImg('banner_src_file',md5($imgName.'0'));
        if($imgSrc){
            $matchInfo['banner_src'] = $imgSrc;
        }
        $imgSrc = $_ENV['qiniu']->uploadQiNiuImg('logo_src_file',md5($imgName.'1'));
        if($imgSrc){
            $matchInfo['logo_src'] = $imgSrc;
        }
        
        if($matchInfo['status']==2 || $matchInfo['status']==3){
            $matchInfo['status']=1;
        }
        
        //参赛费
        $cost = 0;
        if($matchInfo['cost'] && $matchInfo['cost'] != '0.00'){
            $cost = $matchInfo['cost'];
            unset($matchInfo['cost']);
        }
        
        $match_mod = $this->load('match');
        if(!empty($matchInfo['match_id'])){
            $res = $match_mod->update($matchInfo);
            $match_id = $res ? $matchInfo['match_id'] : false;
        }else{
            $match_id = $match_mod->insert($matchInfo);
        }
        
        if(!$match_id){
            exit('添加失败');
        }elseif($cost && !isset($matchInfo['match_id'])){
            $goods_id = $this->load('goods')->addRaceGoods($match_id,33,36,99999,$cost,0);
            $matchInfo['fee_goods_id'] = $goods_id;
            $matchInfo['match_id'] = $match_id;
            $match_mod->update($matchInfo);
        }
        
        echo '<a href="index.php?c=admin&a=matchInfo&match_id='.$match_id.'">操作成功 ------- 查看</a>';
    }
    
    /*
     * 赛事统计
     */
    public function domatchStatistics(){
        $p = common::request('p','R',1);
        $type = common::request('type','R');
        $match_id = common::request('match_id','R');
        $excel = common::request('excel','R',0);
        
        $match_mod = $this->load('match');
        $matchInfo = $match_mod->getMatchInfo($match_id);
        if(empty($type)){
            $type = $matchInfo['match_type']!=1 ? 'user' : 'group';
        }
        $sql = "SELECT count(*) FROM r_match_add WHERE match_id = $match_id AND `type`='user' AND status=1";
        $user_num = $this->db->getOne($sql);
        $sql = "SELECT count(*) FROM r_match_add WHERE match_id = $match_id AND `type`='group' AND status=1";
        $group_num = $this->db->getOne($sql);
        
        //分页
        require FILE . 'lib/page.class.php';
        $listNum = $excel ? 9999 : 20;
        $start = ($p - 1)*$listNum;
        $num = $type=='user'?$user_num : $group_num;
        $page = new Page($num, $listNum);
        $this->view->assign('pageStr',$page->show());
        
        $matchAdd = $match_mod->getMatchAddList($match_id,$type,$start,$listNum);
        foreach($matchAdd as $k=>$row){
            $row = array_merge($row,$match_mod->getStatistics($matchInfo,$row));
            if($row['type']=='group'){
                $group = $this->load('group')->getGroupInfo($row['gid']);
                $row['group_name'] = $group['name'];
            }
            $matchAdd[$k] = $row;
        }
        
        $matchInfo['status'] = common::$matchStatus[$matchInfo['status']];
        
        if($excel){
            include FILE . 'lib/phpexcel/Classes/PHPExcel.php';
            $cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_sqlite3;
            PHPExcel_Settings::setCacheStorageMethod($cacheMethod);
            $PHPExcel = new PHPExcel();
            $sheet = $PHPExcel->getActiveSheet();
            //设置列宽
            $sheet->getColumnDimension('A')->setWidth(10);
            $sheet->getColumnDimension('B')->setWidth(10);
            $sheet->getColumnDimension('C')->setWidth(10);
            $sheet->getColumnDimension('D')->setWidth(30);
            $sheet->getColumnDimension('E')->setWidth(10);
            $sheet->getColumnDimension('F')->setWidth(10);
            $sheet->getColumnDimension('G')->setWidth(30);
            $sheet->getColumnDimension('H')->setWidth(10);
            //表头
            $sheet->setCellValue('A1','#');
            $sheet->setCellValue('B1','uid');
            $sheet->setCellValue('C1','姓名');
            $sheet->setCellValue('D1','联系方式');
            $sheet->setCellValue('E1','总次数');
            $sheet->setCellValue('F1','总里程');
            $sheet->setCellValue('G1','目标数据');
            $sheet->setCellValue('H1','达标情况');
            //填入列表
            foreach($matchAdd as $k=>$v){
                $row = $k+2;
                $sheet->setCellValue('A'.$row,$v['id']);
                $sheet->setCellValue('B'.$row,$v['uid']);
                $sheet->setCellValue('C'.$row,$type=='user' ? $v['name'] : $v['group_name']);
                $str = '电话：'.$v['phone'].'性别';
                $str .= $v['gender']==1 ? '男' : '女';
                $sheet->setCellValue('D'.$row,$str);
                $sheet->setCellValue('E'.$row,$v['total_times']);
                $sheet->setCellValue('F'.$row,$v['total_mileage']);
                $sheet->setCellValue('G'.$row,$v['recent_data']);
                $sheet->setCellValue('H'.$row,$v['dabiao'] ? '达标' : '未达标');
            }
            //保存为2003格式
            $objWriter = new PHPExcel_Writer_Excel5($PHPExcel);
            header("Pragma: public");
            header("Expires: 0");
            header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
            header("Content-Type:application/force-download");
            header("Content-Type:application/vnd.ms-execl");
            header("Content-Type:application/octet-stream");
            header("Content-Type:application/download");

            //多浏览器下兼容中文标题
            $fileName = 'matchExport-'.date('Y-m-d H:i:s');
            $encoded_filename = urlencode($fileName);
            $ua = $_SERVER["HTTP_USER_AGENT"];
            if (preg_match("/MSIE/", $ua)) {
                header('Content-Disposition: attachment; filename="' . $encoded_filename . '.xls"');
            } else if (preg_match("/Firefox/", $ua)) {
                header('Content-Disposition: attachment; filename*="utf8\'\'' . $fileName . '.xls"');
            } else {
                header('Content-Disposition: attachment; filename="' . $fileName . '.xls"');
            }

            header("Content-Transfer-Encoding:binary");
            $objWriter->save('php://output');
        }else{
            $this->view->assign('type',$type);
            $this->view->assign('user_num',$user_num);
            $this->view->assign('group_num',$group_num);
            $this->view->assign('matchInfo',$matchInfo);
            $this->view->assign('matchStatistics',$matchAdd);
            $this->view->display('matchStatistics');
        }
    }

    /**
     * 申诉
     */
    public function docomplain(){
        $id = intval(common::request('id','P'));
        $act = common::request('act','P');
        if(!empty($id)){
            if($act == 'pass'){
                $res = $this->db->query("update r_complain set status=2 where id = $id");
                $data['msg'] = $res ? "操作成功" : "操作失败";
                $data['code'] = $res ? 200 : 100;
            }else{
                $reason = common::request('reason','P','');
                if(empty($reason)){
                    $data['msg'] = "请输入原因";
                    $data['code'] = -1;
                }else{
                    $res = $this->db->query("update r_complain set status=1 where id = $id");
                    $data['msg'] = $res ? "操作成功" : "操作失败";
                    $data['code'] = $res ? 200 : 100;
                }
            }
            echo json_encode($data);
        }else{
            $status = isset($_REQUEST['status']) ? $_REQUEST['status'] : -1;
            if($status == -1){
                $where = " where 1";
                $param = "status=-1";
            }else{
                $where = " where status=$status";
                $param = "status=$status";
            }
            require FILE . 'lib/page.class.php';
            $totalRows = $this->db->getOne("select count(*) from r_complain $where");
            $p = common::request('p','G','1');
            $page = new Page($totalRows,20,$param);
            $offset = ($p-1)*20;
            $data = $this->db->getAll("select * from r_complain $where order by id desc limit $offset,20");
            $pageStr = $page->show();
            $status = ['等待处理','申诉未通过','申诉通过'];
            foreach($data as &$item){
                $actInfo =  $this->load('groupActivity')->getActByAid($item['aid']);
                $item['img'] = !empty($item['img']) ? json_decode($item['img'],true) : [];
                $item['title'] = isset($actInfo['title']) ? $actInfo['title'] : '';
                $item['s'] = $status[$item['status']];

            }
            $this->view->assign('status',$status);
            $this->view->assign('pageStr',$pageStr);
            $this->view->assign('list',$data);
            $this->view->display('complain');
        }

    }

    public function dojoinsList(){
        $aid = common::request('aid','G');
        $gid = common::request('gid','G');
        if(empty($gid)){
            $gids = $this->redis->smembers(REDIS_PREFIX."ACTaccept_".$aid);
            $gids = implode(',',$gids);
            $whereExt = "";
            if(empty($gids)){
                $whereExt .= "";
            }else{
                $whereExt .= " and gid in($gids)";
            }
            $sql = "select r_activity_add.*,i.name as realname,i.phone,i.gender,i.collect_ext_value1,i.collect_ext_value2 from r_activity_add left join r_collect_info as i on r_activity_add.uid=i.uid and r_activity_add.aid=i.aid where r_activity_add.aid=$aid $whereExt";
            $data = $this->db->getAll($sql);
            $show = '';
            foreach($data as &$item){
                $item['nickname'] = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$item['uid'],'nickname');
                $item['name'] = $this->redis->hget(REDIS_PREFIX.'GroupInfo_'.$item['gid'],'name');
                $item['title'] = $this->redis->hget(REDIS_PREFIX.'ActivityInfo_'.$aid,'title');
            }
        }else{
            require FILE . 'lib/page.class.php';
            $totalRows = $this->db->getOne("select count(*) from r_activity_add where aid=$aid and gid=$gid");
            $p = common::request('p','G','1');
            $rows = 20;
            $page = new Page($totalRows,$rows);
            $offset = ($p-1)*$rows;
            $data = $this->db->getAll("select r_activity_add.*,i.name as realname,i.phone,i.gender,i.collect_ext_value1,i.collect_ext_value2 from r_activity_add left join r_collect_info as i on r_activity_add.uid=i.uid and r_activity_add.aid=i.aid where r_activity_add.aid=$aid and gid=$gid limit {$offset},{$rows}");
            $show = $page->show();
            foreach($data as &$info){
                $info['nickname'] = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$info['uid'],'nickname');
                $info['name'] = $this->redis->hget(REDIS_PREFIX.'GroupInfo_'.$gid,'name');
                $info['title'] = $this->redis->hget(REDIS_PREFIX.'ActivityInfo_'.$aid,'title');
            }
        }



        $this->view->assign('data',$data);
        $this->view->assign('pageStr',$show);
        $this->view->display('joinsList');
    }


    /*
     * 有道页面导航
     */
    public function dobbsChannel(){
        $titles = common::request('titles','P');
        $schemes = common::request('schemes','P');
        $sorts = common::request('sorts','P');
        
        $bbsChannel = $this->load('bbs')->getBbsChannel();
        if(empty($bbsChannel)){
            $bbsChannel = array(
                array(
                    'title' => 'ShowTime',
                    'image' => 'http://' . $this->config['host'] . '/static/images/youdao_showtime.png',
                    'scheme' => 'joggers://bbs/showtime',
                ),
                array(
                    'title' => '问答',
                    'image' => 'http://' . $this->config['host'] . '/static/images/youdao_wenda.png',
                    'scheme' => 'joggers://bbs/qa',
                ),
                array(
                    'title' => '装备', 
                    'image' => 'http://' . $this->config['host'] . '/static/images/youdao_gear.png',
                    'scheme' => 'joggers://bbs/gear',
                ),
                array(
                    'title' => '活动',
                    'image' => 'http://' . $this->config['host'] . '/static/images/youdao_huodong.png',
                    'scheme' => 'http://irun.hupu.com/show/activityList',
                ),
            );
            $this->redis->SET(REDIS_PREFIX.'bbsChannel',json_encode($bbsChannel));
        }

        if($sorts){
            foreach($sorts as $key=>$sort){
                if($sort===''){
                    continue;
                }
                if(isset($bbsChannel[$key])){
                    $image = $this->load('qiniu')->uploadQiNiuImg('image_'.$key, md5(time().'bbsMenu_'.$key));
                    $new_bbsChannel[$sort]['image'] = $image ? $image : $bbsChannel[$key]['image'];
                }else{
                    $image = $this->load('qiniu')->uploadQiNiuImg('image_x', md5(time().'bbsMenu_'.$key));
                    $new_bbsChannel[$sort]['image'] = $image ? $image : '';
                }
                $new_bbsChannel[$sort]['title'] = $titles[$key];
                $new_bbsChannel[$sort]['scheme'] = $schemes[$key];
            }
            ksort($new_bbsChannel);
            $bbsChannel = $new_bbsChannel;
            $this->redis->SET(REDIS_PREFIX.'bbsChannel',json_encode($new_bbsChannel));
        }
        $this->view->assign('bbsChannel',$bbsChannel);
        $this->view->display('bbsChannel');
    }
    
    /*
     * 首页装备资讯两个图片按钮
     */
    public function dogearNewsBanner(){
        $titles = common::request('titles','P');
        $schemes = common::request('schemes','P');
        $sorts = common::request('sorts','P');
        
        $gearNewsBanner = $this->load('bbs')->getGearNewsBanner();
        if(empty($gearNewsBanner)){
            $gearNewsBanner = array_fill(0,2,['image'=>'','title'=>'','scheme'=>'']);
        }

        if($sorts){
            foreach($sorts as $key=>$sort){
                if($sort===''){
                    continue;
                }
                if(isset($gearNewsBanner[$key])){
                    $image = $this->load('qiniu')->uploadQiNiuImg('image_'.$key, md5(time().'gearNewsBanner_'.$key));
                    $new_gearNewsBanner[$sort]['image'] = $image ? $image : $gearNewsBanner[$key]['image'];
                }else{
                    $image = $this->load('qiniu')->uploadQiNiuImg('image_x', md5(time().'gearNewsBanner_'.$key));
                    $new_gearNewsBanner[$sort]['image'] = $image ? $image : '';
                }
                $new_gearNewsBanner[$sort]['title'] = $titles[$key];
                $new_gearNewsBanner[$sort]['scheme'] = $schemes[$key];
            }
            $gearNewsBanner = $new_gearNewsBanner;
            $this->redis->SET(REDIS_PREFIX.'gearNewsBanner',json_encode($new_gearNewsBanner));
        }
        $this->view->assign('gearNewsBanner',$gearNewsBanner);
        $this->view->display('gearNewsBanner');
    }

    public function dobbsPush(){
        $newsId = intval(common::request('id','P'));
        if(empty($newsId)){
            $this->view->display('bbsPush');
        }else{
            $newsInfo = $this->load('bbs')->getPostInfo($newsId);
            if(empty($newsInfo) || (isset($newsInfo['is_show']) && $newsInfo['is_show'] == 0)){
                common::tips("该帖子不存在或已删除！");
                return ;
            }
            $pushInfo = $this->db->getRow("select news_id from r_news_push where news_id='$newsId'");
            if(!empty($pushInfo)){
                common::tips("已推送或已在推送队列中！");
                return ;
            }
            $data = [
                'news_id' => $newsId,
                'gender' => common::request('gender','P',0),
                'city' => common::request('city','P'),
                'uids' => trim(common::request('uids','P')),
                'addtime' => time(),
            ];
            $push_time = common::request('push_time','P');
            $data['push_time'] = $push_time ? strtotime($push_time) : '';
            $uids = common::request('uids','P');
            
            $insertId = $this->db->insertRowTable('r_news_push',$data);
            if($insertId > 0){
                common::go("?c=admin&a=bbsPushList");
            }else{
                common::tips("操作失败，请稍后重试！");
            }

        }
    }

    public function dobbsPushList(){
        //删除操作
        $ope = common::request('operate', 'P');
        
        if ($ope == 'del') {
            $pid = common::request('id', 'P');
            
            if ($pid) {
                $this->db->delDataTable('r_news_push', 'id=' . $pid . ' and status=0');
                exit(json_encode(['code' => 0, 'msg' => '操作成功']));
            } else {
                exit(json_encode(['code' => 1, 'msg' => '操作失败']));
            }
        }
        
        $p = common::request('p','G',1);
        $status = isset($_REQUEST['status']) ? $_REQUEST['status'] : -1;
        $where = " 1";
        if($status >= 0){
            $where .= " and status='$status'";
        }
        require FILE . 'lib/page.class.php';
        $totalRows = $this->db->getOne("select count(1) from r_news_push where $where");
        $listRows = 20;
        $offset = ($p-1) * $listRows;
        $page = new Page($totalRows,$listRows,"status=$status");
        $pageStr = $page->show();
        $list = $this->db->getAll("select * from r_news_push where $where order by addtime desc limit {$offset},{$listRows}");
        foreach($list as &$item){
            $newsInfo = $this->load('bbs')->getPostInfo($item['news_id']);
            $title = empty($newsInfo['title']) ? $newsInfo['short_desc'] : $newsInfo['title'];
            $item['title'] = $title;
        }
        $this->view->assign('pageStr',$pageStr);
        $this->view->assign('status',$status);
        $this->view->assign('pushStatus',["等待推送","推送中","已推送"]);
        $this->view->assign('list',$list);
        $this->view->display('bbsPushList');
    }
    public function dogetNewsInfo(){
        $id = intval(common::request('id','G'));
        $newsInfo = $this->load('bbs')->getPostInfo($id);
        if(empty($newsInfo) || (isset($newsInfo['is_show']) && $newsInfo['is_show']==0)){
            echo json_encode(['code'=>100,"msg"=>'这个帖子被兔子吃了']);
        }else{
            $pushInfo = $this->db->getRow("select news_id from r_news_push where news_id='$id'");
            if(!empty($pushInfo)){
                echo json_encode(['code'=>101,'msg'=>"已推送或已在推送队列中！"]);
                exit;
            }
            $title = empty($newsInfo['title']) ? $newsInfo['short_desc'] : $newsInfo['title'];
            echo json_encode(['code'=>200,'title'=>$title]);
        }
    }

    
    /*
     * 话题列表
     */
    public function dotopicList(){
        $name = common::request('name','R','');
        $addtimeStartStr = common::request('addtimeStartStr','R','');
        $addtimeEndStr = common::request('addtimeEndStr','R','');
        $startTimeStr = common::request('startTimeStr','R','');
        $endTimeStr = common::request('endTimeStr','R','');
        $sort = common::request('sort','R','');
        $p = common::request('p','R',1);
        
        $search = compact('name','addtimeStartStr','addtimeEndStr','startTimeStr','endTimeStr','sort');
        $parameter = '&'.urldecode(http_build_query($search, NULL, '&'));
        
        $query = ' where 1';
        if($addtimeStartStr){
            $query .= ' AND addtime >='.strtotime($addtimeStartStr);
        }
        if($addtimeEndStr){
            $query .= ' AND addtime <='.strtotime($addtimeEndStr);
        }

        if($name){
            $query .= " AND name like '%{$name}%'";
        }
        switch($sort){
            case 'post_count_asc':
                $order = 'post_count asc';
                break;
            case 'post_count_desc':
                $order = 'post_count desc';
                break;
            case 'pv_asc':
                $order = 'pv asc';
                break;
            case 'pv_desc':
                $order = 'pv desc';
                break;
            default:
                $order = 'topic_id desc';
                break;
        }
        $query .= ' order by '.$order;
        
        //分页
        require FILE . 'lib/page.class.php';
        $listNum = 50;
        $start = ($p - 1) * $listNum;
        
        $num = $this->db->getOne('select count(*) from r_topic'.$query);
        $page = new Page($num, $listNum, $parameter);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);
        
        $topicList = $this->db->getAll('select * from r_topic'.$query." limit $start,$listNum");
        
        $topic_mod = $this->load('topic');
        foreach($topicList as &$topic){
            $topic = array_merge($topic_mod->getTopicInfo($topic['name']),$topic);
        }
        
        $this->view->assign('search',$search);
        $this->view->assign('topicStatus',common::$topicStatus);
        $this->view->assign('topicList',$topicList);
        $this->view->display('topicList');
    }
    
    /*
     * 话题详情
     */
    public function dotopicInfo(){
        $topic_id = common::request('topic_id','R');
        if($topic_id){
            $topicInfo = $this->db->getRowTable('r_topic',[],'topic_id='.$topic_id);
            $topicInfo['feature_posts'] = str_replace(['[',']'],'',$topicInfo['feature_posts']);
        }else{
            $topicInfo = [
                'topic_id' => '',
                'name' => '',
                'short_desc' => '',
                'status' => 0,
                'sort' => 0,
                'thumb_img' => '',
                'feature_posts' => ''
            ];
        }
        $this->view->assign('topicStatus',common::$topicStatus);
        $this->view->assign('topicInfo',$topicInfo);
        $this->view->display('topicInfo');
    }
    
    /*
     * 话题修改
     */
    public function dotopicAction(){
        $topic_id = common::request('topic_id','R');
        $name = common::request('name','P');
        $short_desc = common::request('short_desc','P');
        $status = common::request('status','P');
        $action = common::request('action','R');
        $feature_posts = common::request('feature_posts','R','');
        
        if($action == 'delete' && $topic_id){
            $this->load('topic')->destroy($topic_id);
        }else{
        
            if(!$name){
                exit('参数不完整');
            }
            
            $feature_posts = '['.trim($feature_posts).']';
            if(!common::is_json($feature_posts)){
                exit('帖子id格式错误');
            }
            
            $data = compact('name','short_desc','status','feature_posts');
            
            if($topic_id){
                $data['topic_id'] = $topic_id;
                $this->load('topic')->update($data);
            }else{
                $sql = "select topic_id from r_topic where name='{$name}' limit 1";
                if($this->db->getOne($sql)){
                    die('<a href="index.php?c=admin&a=topicList">话题已存在....返回</a>');
                }
                
                $data['uid'] = $this->realUser['uid'];
                $this->load('topic')->insert($data);
            }
        }
        
        echo '<a href="index.php?c=admin&a=topicList">操作成功....返回</a>';
    }
    
    /*
     * 推荐的话题列表
     */
    public function dofeaturedTopic(){
        $topic_id = common::request('topic_id','P');
        $sort = common::request('sort','P');
        $home = common::request('home','P',[]);
        
        $topic_mod = $this->load('topic');
        $topicList = $topic_mod->getFeaturedTopics();
        if($topic_id && $sort){
            $topicList = [];
            foreach($topic_id as $key=>$id){
                if(!$id){
                    continue;
                }
                $name = $this->db->getOne('select name from r_topic where topic_id='.$id);
                $topicList[$sort[$key]] = [
                    'topic_id' => $id,
                    'name' => $name,
                    'sort' => $sort[$key],
                    'home' => in_array($id,$home) ? 1: 0
                ];
            }
            ksort($topicList);
            $this->redis->set(REDIS_PREFIX.'FeaturedTopic',json_encode($topicList));
        }
        
        $this->view->assign('topicList',$topicList);
        $this->view->display('featuredTopicList');
    }

    /*
     * 完赛、擂主勋章发放
     */
    public function domedalGive()
    {
        $beginTime  = time(); //活动开始时间
        $endTime    = $beginTime; //活动结束时间
        
        if (common::request('doGive', 'P'))
        {
            set_time_limit(0);
            ini_set('memory_limit','1024M');
            $beginTime  = common::request('begintime', 'P'); //活动开始时间
            $endTime    = common::request('endtime', 'P'); //活动结束时间
            $finishGrp  = common::request('wansai', 'P'); //完赛组
            $leizhuGrp  = common::request('leizhu', 'P'); //擂主组
            $sourceDate = date('Ymd'); //发勋章日期
            $addTime    = time(); //勋章发放时间
            $echoStr    = '';
            
            if (empty($beginTime) || empty($endTime)) {
                echo 'time error!<br /><br /><a href="">go back</a>';
                exit;
            }
            
            $beginTime  = strtotime($beginTime);
            $endTime    = strtotime($endTime);

            $echoStr .= date('Y-m-d H:i:s') . ' | begin...' . "<br />";

            if (!empty ($finishGrp))
            {
                $echoStr .= "<br />发放完赛勋章：<br />";
                //排除已退群成员
                $uids = $this->db->getCol('select uid from r_gmember where gid in (' . $finishGrp . ') and (role!=3 or (role=3 and lastupdate > '.$endTime.')) group by uid');
//                $uids = $this->db->getCol('select uid from r_gmember where gid in (' . $finishGrp . ') group by uid');

                foreach($uids as $k => $uid)
                {
                    $did = $this->db->getOne("select did from r_data where addtime between {$beginTime} and {$endTime} and overSpeed=0 and uid='{$uid}' and mileage>=1 limit 1");

                    if($did)
                    {
                        $medalRecord = $this->db->getOne("select count(1) from r_medal_record where medal_id=1008 and uid={$uid} and add_time>={$endTime}");

                        if($medalRecord < 1)
                        {
                            $medal   = [];
                            $medal[] = 1008;
                            $insertData = array('uid'=>$uid,'medal_id'=>1008,'add_time'=>$addTime,'source_data'=>$sourceDate,'isCustom'=>1);
                            $this->db->insertRowTable('r_medal_record',$insertData);
                            $medal = json_encode($medal);
                            $this->db->query("update r_data set medal='{$medal}' where did='{$did}'");
                        }
                    }

                    $echoStr .= date('Y-m-d H:i:s') . ' | putong:' . $k . "\n";
                }
            }
            
            if (!empty($leizhuGrp))
            {
                $echoStr .= "<br /><br />发放擂主勋章：<br />";
                //排除已退群成员
                $uids = $this->db->getCol('select uid from r_gmember where gid in (' . $finishGrp . ') and (role!=3 or (role=3 and lastupdate > '.$endTime.')) group by uid');
//                $uids = $this->db->getCol('select uid from r_gmember where gid in (' . $leizhuGrp . ') group by uid');

                foreach($uids as $k => $uid)
                {
                    $did = $this->db->getOne("select did from r_data where addtime between {$beginTime} and {$endTime} and overSpeed=0 and uid='{$uid}' and mileage>=1 limit 1");

                    if($did)
                    {
                        $medalRecord = $this->db->getOne("select count(1) from r_medal_record where medal_id=1009 and uid={$uid} and add_time>={$endTime}");

                        if($medalRecord < 1)
                        {
                            $medal   = [];
                            $medal[] = 1009;
                            $insertData = array('uid'=>$uid,'medal_id'=>1009,'add_time'=>$addTime,'source_data'=>$sourceDate,'isCustom'=>1);
                            $this->db->insertRowTable('r_medal_record',$insertData);
                            $medal = json_encode($medal);
                            $this->db->query("update r_data set medal='{$medal}' where did='{$did}'");
                        }
                    }

                    $echoStr .= date('Y-m-d H:i:s') . ' | leizhu:' . $k . "\n";
                }
            }

            $echoStr .= '<br />' . date('Y-m-d H:i:s') . ' | end.' . '<br /><br /><a href="">go back</a>';
            echo $echoStr;
            exit;
        } 
        else
        {
            $this->view->assign('begintime', $beginTime);
            $this->view->assign('endtime', $endTime);
            $this->view->display('medalGive');
        }
    }

    public function doblackUser(){
        $uid = common::request('id',"R");
        $userInfo = $this->load('client')->getUserInfo($uid);
        if(empty($userInfo)){
            common::tips("不存在该用户！");
            exit;
        }
        if($_POST){
            $forbid = common::request('forbid','P');
            $stime = strtotime(common::request("stime",'P'));
            $etime = strtotime(common::request("etime",'P'));
            $mark = common::request('mark','P');
            if(empty($forbid)){
                common::tips("请选择禁言模块！");
                exit;
            }
            if($stime >= $etime){
                common::tips("时间不正确！");
                exit;
            }
            $lastCid = $this->db->getOne("select lastcid from r_user where uid='{$uid}'");
            $cid = isset($lastCid) ? $lastCid : 0;
            $client = $this->load('client')->getClientOrPushTokenByCid(1,$cid);
            $forbid = json_encode($forbid);
            $addtime = time();
            $data = compact('forbid','stime','etime','mark','uid','addtime');
            $insertId = $this->db->insertRowTable("r_black_user",$data);
            if($insertId > 0){
                $time = $etime - time();
                if($time > 5){
                    $this->redis->setex(REDIS_PREFIX."BlackUser_".$uid,$time,$forbid);
                    !empty($client) && $this->redis->setex(REDIS_PREFIX."BlackUser_".$client,$time,$forbid);
                }else{
                    $this->redis->del(REDIS_PREFIX."BlackUser_".$uid);
                    $this->redis->del(REDIS_PREFIX."BlackUser_".$client);
                }

                common::tips('设置成功！',"?c=admin&a=blackList");
            }else{
                common::tips('添加失败，请重试！');
            }
        }else{
            $info = $this->db->getRow("select * from r_black_user where uid='$uid'");
            $info['forbid'] = json_decode($info['forbid'],true);

            $this->view->assign('id',$uid);
            $this->view->assign('func',$this->_function);
            $this->view->assign('info',$info);
            $this->view->assign('nickname',$userInfo['nickname']);
            $this->view->display("blackUser");
        }
    }

    public function doblackList(){
        $p = common::request('p','G',1);
        require FILE . 'lib/page.class.php';
        $listNum = 20;
        $start = ($p - 1) * $listNum;
        $num = $this->db->getOne('select count(*) from r_black_user');
        $page = new Page($num, $listNum);
        $pageStr = $page->show();
        $list = $this->db->getAll("select * from r_black_user order by addtime desc limit {$start},{$listNum}");
        foreach($list as &$val){
            $userInfo = $this->load("client")->getUserInfo($val['uid']);
            $clientInfo = $this->db->getRow("select client,client_type from r_client where cid = '".$userInfo['cid']."'");
            $source = "";
            if(!empty($userInfo['qq'])){
                $source .= "QQ <br>";
            }
            if(!empty($userInfo['sina'])){
                $source .= "新浪微博 <br>";
            }
            if(!empty($userInfo['weixin'])){
                $source .= "微信 <br>";
            }
            if(!empty($userInfo['renren'])){
                $source .= "人人 <br>";
            }
            if(!empty($userInfo['phone'])){
                $source .= "手机";
            }
            $forbid = json_decode($val['forbid'],true);

            $func = "";
            foreach($forbid as $item){
                $func.= $this->_function[$item]."<br>";
            }
            $val['forbid'] = $func;
            $val['nickname'] = $userInfo['nickname'];
            $val['totalMileage'] = $userInfo['total_mileage'];
            $val['source'] = $source;
            $val['clientId'] = isset($clientInfo['client']) ? $clientInfo['client'] : "";
            $val['type'] = isset($clientInfo['client_type']) ? ( $clientInfo['client_type'] == 1 ? '安卓' : 'IOS') : "";
        }
        $this->view->assign('list',$list);
        $this->view->assign('pageStr', $pageStr);
        $this->view->display('blackList');

    }
    
    /*
     * url黑名单
     */
    public function dourlBlackList(){
        $content = common::request('content','P');
        
        $redisKey = REDIS_PREFIX.'URLBlackList';
        if($content){
            if(!common::is_json($content)){
                die('格式错误，<a href="index.php?c=admin&a=urlBlackList">点击返回</a>');
            }
            $this->redis->set($redisKey,$content);
        }
        
        $content = $this->redis->get($redisKey);
        if(!$content){
            $content = '[]';
        }
        $this->view->assign('content',$content);
        $this->view->display('urlBlackList');
    }

    /*
     * 帖子可打赏正能量列表
     */
    public function dopostPayEnergyList(){
        $news_id = common::request('news_id','R',0);
        $pay_energy_list = common::request('pay_energy_list','P');
        $delete = common::request('delete','G');
        
        $redisKey = REDIS_PREFIX.'PostPayEnergyList';
        
        if($delete && isset($news_id)){
            $payEnergyList = json_decode($this->redis->get($redisKey),true);
            unset($payEnergyList[$news_id]);
            $this->redis->set($redisKey,json_encode($payEnergyList));
        }else if(isset($news_id) && $pay_energy_list){
            if(!common::is_json($pay_energy_list)){
                die('格式错误，<a href="c=admin&a=postPayEnergyList">点击返回</a>');
            }
            $payEnergyList = json_decode($this->redis->get($redisKey),true);
            $payEnergyList[$news_id] = $pay_energy_list;
            $this->redis->set($redisKey,json_encode($payEnergyList));
        }
        
        if(!$this->redis->exists($redisKey)){
            $payEnergyList = [
                0 => '[1,3,5,7,9]'
            ];
            $this->redis->set($redisKey,json_encode($payEnergyList));
        }else{
            $payEnergyList = json_decode($this->redis->get($redisKey),true);
        }
        
        $this->view->assign('payEnergyList',$payEnergyList);
        $this->view->display('postPayEnergyList');
    }
    
    /*
     * 用户标签列表
     */
    public function douserTagList(){
        $id = common::request('id','P');
        $tag = common::request('tag','P');
        
        $redisKey = REDIS_PREFIX.'UserTagList';
        if(!$this->redis->exists($redisKey)){
            $this->redis->set($redisKey,'[]');
        }
        
        if(is_array($id) && is_array($tag) && count($id)==count($tag)){
            foreach($id as $k=>$v){
                if(!is_numeric($v)){
                    unset($id[$k]);
                    unset($tag[$k]);
                }
            }
            $userTagList = array_combine($id,$tag);
            $this->redis->set($redisKey,json_encode($userTagList));
        }
        
        $userTagList = json_decode($this->redis->get($redisKey),true);
        
        
        $this->view->assign('userTagList',$userTagList);
        $this->view->display('userTagList');
    }
    
    /*
     * 给用户添加标签
     */
    public function douserTag(){
        $uid = common::request('uid','R');
        $tagIds = common::request('tagIds','P');
        $userTagIdsStr = common::request('userTagIdsStr','P');
        if(!$uid){
            die('uid为空，<a href="index.php?c=admin&a=userList">点击返回</a>');
        }
        
        if($userTagIdsStr){
            if(!isset($tagIds)){
                $tagIds = [];
            }
            $oldUserTagIds = json_decode($userTagIdsStr,true);
            foreach($oldUserTagIds as $tagId){
                if(!in_array($tagId,$tagIds)){
                    $this->db->delDataTable('r_usertag',"tagId=$tagId AND uid=$uid");
                }
            }
            $addtime = time();
            foreach($tagIds as $tagId){
                $this->db->update("replace into r_usertag set tagId=$tagId,uid=$uid,addtime=$addtime");
            }
        }
        
        $sql = "SELECT tagId FROM r_usertag where uid = $uid";
        $userTagIds = $this->db->getCol($sql);
        
        $redisKey = REDIS_PREFIX.'UserTagList';
        $userTagList = json_decode($this->redis->get($redisKey),true);
        
        $this->view->assign('userTagIds',$userTagIds);
        $this->view->assign('userTagIdsStr',json_encode($userTagIds));
        $this->view->assign('userTagList',$userTagList);
        $this->view->assign('uid',$uid);
        $this->view->display('userTag');
    }

    public function douploadImage()
    {
        
    }
    
    /*
     * 群组概览
     */
    public function doGroupStatisticGeneral(){
        $gid = common::request('gid','R');
        $day = common::request('day','R',0);
        $date = common::request('date','R');
        if(!$gid){
            die('参数不正确');
        }
        if($date){
            $stime = strtotime($date.' 00:00:00');
        }else{
            $stime = strtotime(date('Y-m-d 00:00:00'))-$day*24*3600;
        }
        $etime = $stime + 24*3600;
        
        $where = " gid={$gid} and addtime between $stime and $etime";
        $sql = "select count(distinct(uid)) from r_group_add where $where";
        $gmember = $this->db->getOne($sql);
        $sql = "select count(*) from r_group_activity where $where";
        $activity = $this->db->getOne($sql);
        $sql = "select count(*) from r_group_news where $where";
        $news = $this->db->getOne($sql);
        $sql = "select count(distinct(uid)) from r_group_run where $where";
        $run_user = $this->db->getOne($sql);
        $sql = "select sum(mileage) from r_group_run where $where";
        $mileage = $this->db->getOne($sql);
        
        $this->view->assign('gmember',$gmember);
        $this->view->assign('activity',$activity);
        $this->view->assign('news',$news);
        $this->view->assign('run_user',$run_user);
        $this->view->assign('mileage',$mileage);
        $this->view->assign('gid',$gid);
        $this->view->display('groupStatisticGeneral');
    }
    
    /*
     * 黑名单记录
     */
    public function dobadwordsLog(){
        $etime = strtotime('last monday');
        $stime = $etime - 7*24*3600;
        
        $data = $this->load('log')->getBadwordsLog($stime,$etime);
        
        echo "<table>";
        echo "<tr><th>序号</th><th>信息类别</th><th>关键词</th><th>URL</th><th>所属IDC</th><th>QQ号</th><th>电子邮箱</th><th>手机号</th><th>生产厂家</th><th>地址</th><th>联系人</th><th>注册时间</th><th>注册IP</th><th>uid</th><th>发帖IP</th><th>发帖人所在地</th><th>发帖时间</th><th>上报网站名称</th><th>处置结果</th>";
        foreach($data as $row){
            if(!$row){
                continue;
            }
            
            echo "<tr>";
            echo "<td>".$row['id']."</td>";
            echo "<td>".$row['cat']."</td>";
            echo "<td>".$row['badwords']."</td>";
            echo "<td>已删帖</td>";
            echo "<td>UCLOUD</td>";
            echo "<td>".$row['qq']."</td>";
            echo "<td></td>";
            echo "<td>".$row['phone']."</td>";
            echo "<td></td>";
            echo "<td></td>";
            echo "<td>".$row['nickname']."</td>";
            echo "<td>".date('Y-m-d H:i:s',$row['register_time'])."</td>";
            echo "<td></td>";
            echo "<td>".$row['uid']."</td>";
            echo "<td>".$row['ip']."</td>";
            echo "<td>".$row['city']."</td>";
            echo "<td>".date('Y-m-d H:i:s',$row['addtime'])."</td>";
            echo "<td>虎扑跑步</td>";
            echo "<td>删帖</td>";
            echo "</tr>";
        }
        
        echo "</table>";
    }
    
    public function doclientExcepCount() {
        $this->in_logDb();
        $sTime = common::request('start_time', 'P');
        $eTime = common::request('end_time', 'P');
        
        if (empty($sTime) && empty($eTime)) {
            $eTime = time();
            $sTime = strtotime(date('Ymd', $eTime)) -  6 * 86400;
        } else if (empty($sTime)) {
            $eTime = strtotime($eTime);
            $sTime = strtotime(date('Ymd', $eTime)) -  6 * 86400;
        } else if (empty($eTime)) {
            $sTime = strtotime($sTime);
            $eTime = time();
        } else {
            $sTime = strtotime($sTime);
            $eTime = strtotime($eTime);
        }
        
        $sql = 'select total_num, except_num, date_time, device_type, device_release from client_odd_statistics where date_time between ' . $sTime . ' and ' . $eTime ;

        $datas = $this->logDb->getAll($sql);
        $weekDatas = $excpDatas = $serNames = $dateArr = [];
        $chatOpt = [
            'chart'      => ['type' => 'column'],
            'title'     => '客户端异常记录统计',
            'xAxis'     => ['categories' => [], 'title' => ['text' => '日期']],
            'yAxis'     => ['min' => 0, 'title' => ['text' => '数量'], 'allowDecimals' => false],
            'tooltip'   => ['formatter' => null],
            'series'    => [['name' => '总数', 'data' => []], ['name' => '异常数', 'data' => []]]
        ];
             
        if (!empty($datas)) {
            foreach ($datas as $k => $v) {          
                $date_str = date('Y.m.d', $v['date_time']);
                !in_array($date_str, $dateArr) && $dateArr[] = $date_str;

                if (!isset($weekDatas[$date_str])) {
                    $weekDatas[$date_str] = [
                        'total' => 0,
                        'excep' => 0
                    ];
                }
                
                if (!isset($excpDatas[$date_str])) {
                    $excpDatas[$date_str] = [];
                }

                $weekDatas[$date_str]['total'] += $v['total_num'];
                $weekDatas[$date_str]['excep'] += $v['except_num'];
                
                if ($v['except_num']) {
                    $sKey = $v['device_type'].' (' . $v['device_release'] . ')';
                    !in_array($sKey, $serNames) && $serNames[] = $sKey;
                    $excpDatas[$date_str][$sKey] = $v['except_num'];
                }
            }

            if (!empty($serNames)) {
                $tArr = array_values(array_slice($excpDatas, -1, 1));
                
                if (!empty($tArr)) {
                    $chatOpt['series'] = [];
                    $srk = 0;
                    foreach ($serNames as $nk => $nv) {
                        if (!empty($tArr[0][$nv])) {
                            !isset($chatOpt['series'][$srk]['name']) && $chatOpt['series'][$srk]['name'] = $nv;
                            $chatOpt['series'][$srk++]['data'][] = empty($tArr[0][$nv]) ? 0 : intval($tArr[0][$nv]);
                       }
                    }
                }
            }
            
            $chatOpt['xAxis']['categories'][] = $dateArr[count($dateArr) - 1]; 
        }
 
        $viewDatas = [
            'excp'      => $excpDatas,
            'week'      => $weekDatas,
            'chart'     => json_encode($chatOpt),
            'sTime'     => date('Y-m-d', $sTime),
            'eTime'     => date('Y-m-d', $eTime),
            'timeDur'   => date('Y.m.d', $sTime) . '-' . date('Y.m.d', $eTime),
            'dateArr'   => $dateArr,
            'series'    => $serNames
        ];
  
        $this->view->assign('viewDatas', $viewDatas);
        $this->view->display('clientExcepCount');
    }

    /**

     * 安卓包管理列表
     */
    public function dogetPackageList()
    {
        $listNum = 10;
        $p = common::request('p', 'G', 1);
        $start = ($p - 1) * $listNum;
        $info = $this->db->getAll("select * from r_app_package order by create_time desc limit $start,$listNum");
        $total = $this->db->getOne("select count(1) as cnt from r_app_package");
        $this->view->assign('info', $info);
        require FILE . 'lib/page.class.php';
        $page = new Page($total, $listNum);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);
        $this->view->display('appPackage');
    }

    /**
     * 上传安装包
     */
    public function douploadAppPackage() {
        set_time_limit(0);
        if (!$_FILES || ($_FILES['apkFile']['size'] == 0)) {
            //echo json_encode(array('status'=>'fail','error_msg'=>'请选择上传文件!'));
            common::tips('请选择上传文件');
            exit;
        }
        /*解析安卓apk包中的压缩XML文件，还原和读取XML内容
          依赖功能：需要PHP的ZIP包函数支持。
        */
        $appObj = $this->loadLib('apkparser');
        $targetFile = $_FILES['apkFile']['tmp_name'];//apk所在的路径地址
        $res   = $appObj->open($targetFile);
        if (!$res) {
            common::tips('获取包信息失败');
            exit;
        }
        $appName = $appObj->getAppName();     // 应用名称
        $appPackageName = $appObj->getPackage();    // 应用包名
        $appVersionName = $appObj->getVersionName();  // 版本名称
        $appVersionCode = $appObj->getVersionCode();  // 版本代码

        if (!trim($appPackageName)) {
            common::tips('获取不到应用包名');
            exit;
        }

        if (!trim($appVersionName)) {
            common::tips('获取不到应用包版本名称');
            exit;
        }

        //var_dump('应用名称:'.$appName,'应用包名:'.$packageName,'版本名称:'.$versionName,'版本代码:'.$versionCode);exit;

//        //版本号
//        $version = common::request('version', 'P',null);
//        if (!$version) {
//            //echo json_encode(array('status'=>'fail','error_msg'=>'版本号参数丢失'));
//            common::tips('版本号参数丢失');
//            exit;
//        }
//        //检测版本号是否重复
//        $versionNumber = common::versionToNumber($version);
        $versionNumber = common::request('versionCode','P',0);
        if (!$versionNumber || !preg_match('/^\d+$/',$versionNumber,$match)) {
            //echo json_encode(array('status'=>'fail','error_msg'=>'版本号有误'));
            common::tips('输入框版本号有误');
            exit;
        }

        //检测版本号是否一致
        if (!$appVersionCode) {
            common::tips('获取不到应用包版本号');
            exit;
        }

        if (!preg_match('/^\d+$/',$appVersionCode,$match)) {
            common::tips('应用包版本号有误');
            exit;
        }

        if ($appVersionCode != $versionNumber) {
            common::tips('输入框的版本号与应用包版本号不一致');
            exit;
        }

        $existINfo =  $this->db->getRow("select * from r_app_package where version_num=$versionNumber");
        if ($existINfo) {
           // echo json_encode(array('status'=>'fail','error_msg'=>'重复的版本号'));
            common::tips('重复的版本号');
            exit;
        }

        $num = strrpos($_FILES['apkFile']['name'],'.');
        if ($num === false) {
            //echo json_encode(array('status'=>'fail','error_msg'=>'文件名有误'));
            common::tips('文件名有误');
            exit;
        }
        $packName = substr($_FILES['apkFile']['name'],0,$num).'-'.$versionNumber.time();
        $gearImg =  $this->load('qiniu')->uploadQiNiuApk('apkFile', md5($packName));
        if (!$gearImg) {
            //echo json_encode(array('status'=>'fail','error_msg'=>'上传失败'));
            common::tips('上传失败');
            exit;
        }

        //写入表
        $insertData = ['name'=>$appPackageName,'version_name'=>$appVersionName,'version_num'=>$versionNumber,'create_time'=>time(),'file_hash'=>hash_file('MD5',$gearImg),'file_url'=>$gearImg];
        $this->db->insertRow('r_app_package', $insertData, mysqldb::INSERT_ON_UPDATE);
        common::tips('上传成功','?c=admin&a=getPackageList');
        //echo json_encode(array('status'=>'ok'));
    }


    /**
     * ajax 设置安装包状态
     */
    public function doajaxsetPackageStatus() {
        $packageId = common::request('apkId','R',0);
        $status = common::request('status','R',0);
        if (!$packageId) {
            echo  json_encode(array('status'=>'fail','error_msg'=>'参数丢失'));exit;
        }
        if (!$info = $this->db->getRow("select * from r_app_package where id=$packageId")) {
            echo  json_encode(array('status'=>'fail','error_msg'=>'安装包不存在'));exit;
        }
        if ($status == 1) {
            //取消其他包的更新状态
            $this->db->update("update  r_app_package set status=0 where status=1");
            $this->db->update("update  r_app_package set status=1 where id=$packageId");
        } else {
            $this->db->update("update  r_app_package set status=0 where id=$packageId");
        }
        echo  json_encode(array('status'=>'ok','error_msg'=>'成功','url'=>'?c=admin&a=getPackageList'));exit;
    }

    /**
     * 设置安装包
     */
    public function dosetAppPackage() {
        $id = (int)common::request('id','R',0);
        if (!$id) {
            echo  json_encode(array('status'=>'fail','error_msg'=>'参数丢失'));exit;
        }
        if (isset($_POST['id']) && $_POST['id']) {
            $channel_type = (int)common::request('channelType','R',0);
            $channel_code = common::request('channelCode','R',0);
            $is_force_update = (int)common::request('isForce','R',0);
            $force_update_version = common::request('forceVersion','R',0);
            $update_txt = common::request('updateTxt','R','');

            if (!in_array($channel_type,array(1,5))) {
                echo  json_encode(array('status'=>'fail','error_msg'=>'更新渠道不存在'));exit;

            }
            $sql = 'channel_type='.$channel_type;
            if ($channel_type == 5) {//部分渠道逗号隔开
                if (!$channel_code) {
                    echo  json_encode(array('status'=>'fail','error_msg'=>'部分渠道值不能为空'));exit;
                }
                $sql .= ',channel_code='."'$channel_code'";
            }

            $sql .= ',is_force_update='.$is_force_update;
            if ($is_force_update == 5) {
                $sql .= ',is_force_update='.$is_force_update;
                if (!$force_update_version) {
                    echo  json_encode(array('status'=>'fail','error_msg'=>'请选择强制更新的版本'));exit;
                }
                $sql .= ',force_update_version='."'$force_update_version'";
            }
            if ($update_txt) {
                $sql .= ',update_txt='."'$update_txt'";
            } else {
                $sql .= ',update_txt='."''";
            }

            $result = $this->db->update(
                "update r_app_package set $sql where id=$id"
            );
            if (!$result) {
                echo  json_encode(array('status'=>'fail','error_msg'=>'设置失败'));exit;
            }
            echo  json_encode(array('status'=>'ok','error_msg'=>'成功','url'=>'?c=admin&a=getPackageList'));exit;
        } else {
            // 查询安装包设置信息
            $info = $this->db->getRow("select * from r_app_package where id=$id");
            if (!$info) {
                echo  json_encode(array('status'=>'fail','error_msg'=>'安装包不存在'));exit;
            }
            $this->view->assign('id',$id);
            $this->view->assign('info',$info);
            //历史安装包版本
            $arrVersion  = $this->db->getAll("select version_num from r_app_package where version_num<={$info['version_num']} order by version_num desc");
            $this->view->assign('arrVersion',$arrVersion);
            $this->view->display('setAppPackage');
        }
    }

    /**
     * 短信记录
     */
    public function dogetMobileCodeList() {
        $mobile = common::request('mobile','R','');
        $listNum = 20;
        $p = common::request('p', 'G', 1);
        $start = ($p - 1) * $listNum;
        $parameter = '';
        $where = '1=1';
        if (trim($mobile)) {
            $where .=' and mobile like '."'%$mobile%'";
            $parameter = '&mobile='."$mobile";
        }
        $info = $this->db->getAll("select * from r_mobile_code where $where order by id desc limit $start,$listNum");
        $total = $this->db->getOne("select count(1) as cnt from r_mobile_code");
        $this->view->assign('info', $info);
        require FILE . 'lib/page.class.php';
        $page = new Page($total, $listNum, $parameter);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);
        $this->view->assign('mobile', $mobile);
        $this->view->display('mobileCodeList');
    }

    /**
     * 投诉列表
     * @return [type] [description]
     */
    public function docomplaintsList(){
        $p = common::request('p', 'G', 1);   //页码
        
        $isSearch = common::request('s', 'P','');
        if($isSearch == 'search'){
            $p = 1;
        }
        $news_id = common::request('news_id', 'R','');
        $reason = common::request('reason', 'R','');
        
        $countSql = "select count(1) from (select b.c_id from (select c.* from r_complaints c right join r_news n on c.news_id = n.news_id where c.status = 0 and n.is_show=1 group by uid,news_id,reason) b group by news_id) a";
       
        if(!empty($news_id) && !empty($reason)){
            $countSql = "select count(1) from (select b.c_id from (select c.* from r_complaints c right join r_news n on c.news_id = n.news_id where c.status = 0 and c.news_id = '$news_id' and c.reason = '$reason' and n.is_show=1 group by uid,news_id,reason) b group by news_id) a";
        }else{
            if(!empty($news_id)){
                $countSql = "select count(1) from (select b.c_id from (select c.* from r_complaints c right join r_news n on c.news_id = n.news_id where c.status = 0 and c.news_id = '$news_id' and n.is_show=1 group by uid,news_id,reason) b group by news_id) a";
            }
            if(!empty($reason)){
                $countSql = "select count(1) from (select b.c_id from (select c.* from r_complaints c right join r_news n on c.news_id = n.news_id where c.status = 0 and c.reason = '$reason' and n.is_show=1 group by uid,news_id,reason) b group by news_id) a";
            }
        }

        $search = compact('news_id','reason');
        $offset = 20;
        $num = $this->db->getone($countSql);

        $parameter = "&news_id=".$news_id."&reason=".$reason;
        //分页
        require FILE . 'lib/page.class.php';
        $page = new Page($num, $offset,$parameter);
        $pageStr = $page->show();

        $this->view->assign('pageStr', $pageStr);

        $start = ($p - 1) * $offset;

        $sql = "select b.c_id,b.news_id,b.uid,b.reason,count(1) as reasonCount from (select c.*,count(1) from r_complaints c right join r_news n on c.news_id = n.news_id where c.status = 0 and n.is_show=1 group by uid,news_id,reason) b group by news_id,reason";

        if(!empty($news_id) && !empty($reason)){
            $sql = "select b.c_id,b.news_id,b.uid,b.reason,count(1) as reasonCount from (select c.*,count(1) from r_complaints c right join r_news n on c.news_id = n.news_id where c.status = 0 and c.news_id = '$news_id' and c.reason = '$reason' and n.is_show=1 group by uid,news_id,reason) b group by news_id,reason";
        }else{
            if(!empty($news_id)){
                $sql = "select b.c_id,b.news_id,b.uid,b.reason,count(1) as reasonCount from (select c.*,count(1) from r_complaints c right join r_news n on c.news_id = n.news_id where c.status = 0 and c.news_id = '$news_id' and n.is_show=1 group by uid,news_id,reason) b group by news_id,reason";
            }
            if(!empty($reason)){
                $sql = "select b.c_id,b.news_id,b.uid,b.reason,count(1) as reasonCount from (select c.*,count(1) from r_complaints c right join r_news n on c.news_id = n.news_id where c.status = 0 and c.reason = '$reason' and n.is_show=1 group by uid,news_id,reason) b group by news_id,reason";
            }
        }

        $setList = $this->db->getall($sql);
        
        //投诉理由字典
        $reasonArray = array(
            1 => '政治或政策谣言',
            2 => '色情或暴力',
            3 => '诈骗或广告',
            4 => '恶意攻击',
            5 => '其他'
        );
        $listInfo = array();
        if($setList)
        {
            $i = 0;
            foreach ($setList as & $v) {
                //根据帖子id查询投诉数量
                $countInfo = $this->load('bbs')->getComplaintsCount($v['news_id']);
                $reasonName = array();
                foreach ($countInfo as &$cv) 
                {
                    $reasonName[] = $reasonArray[$cv['reason']].'('.$cv['count'].')';
                }
                $listInfo[$i]['news_id'] = $v['news_id'];
                $listInfo[$i]['reasonName'] = implode(',', $reasonName);
                $i++;
            }
            
            $listInfo = array_unique($listInfo, SORT_REGULAR);
            if(count($listInfo) > $offset){
                $listInfo = array_slice($listInfo, $start, $offset);
            }
        }
        
        $this->view->assign('list', $listInfo);
        $this->view->assign('search', $search);
        $this->view->display('complaintsList');
    }

    /**
     * 删除投诉(包含帖子)
     */
    public function dodelComplaints()
    {
        $news_id = common::request('newsid', 'G');

        if (!empty($news_id))
        {
            //删除投诉列表
            $cid = $this->db->update("update r_complaints set status = 1 where news_id = {$news_id}");
            //删除帖子
            $this->db->update("update r_news set is_show = 0 where news_id = {$news_id}");
            //重新缓存
            $result = $this->db->getRowTable('r_news', array(), "news_id = '{$news_id}'");
            if($result)
            {
                $this->redis->hmset(REDIS_PREFIX . 'NewsInfo_'. $news_id, $result);
            }

            //删除该帖子的投诉次数
            $this->db->update("delete from r_complaints_count where news_id = {$news_id}");
        }
        
        $this->docomplaintsList();
    }

    /**
     * 九月跑步运动会管理后台
     */
    public function dorunningSep()
    {
        $p = common::request('p', 'G', 1);   //页码
        
        //中奖情况
        $setList = $this->db->getall("select * from r_winning_info where acttype = 1");
        //奖品字典
        $prizeInfo = array(
            '1' => 'Apple watch',
            '2' => '跑鞋',
            '3' => '压缩腿套',
            '4' => '虎扑跑步定制速干衣',
            '5' => '跑步书籍',
            '6' => '虎扑跑步定制记事本'
        );
        foreach ($setList as &$v) {
            $v['prizeName'] = $prizeInfo[$v['prize']];
        }

        $countList = $this->db->getAll("select * from r_running_prize_sep where acttype = 1");
        foreach ($countList as &$v) {
            $v['prizeName'] = $prizeInfo[$v['prize']];
        }
        

        //参与情况  
        $joinCount = "select count(1) from r_sports_september where acttype = 1";

        $offset = 20;
        $num = $this->db->getOne($joinCount);

        //分页
        require FILE . 'lib/page.class.php';
        $page = new Page($num, $offset);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);

        $start = ($p - 1) * $offset;

        $joinInfo = $this->db->getAll("select s.uid,u.addtime,SUM(d.mileage) as mileage,COUNT(did) as count,s.draw_count from r_sports_september s LEFT JOIN r_user u ON s.uid = u.uid LEFT JOIN r_data d ON s.uid = d.uid WHERE IF(d.updatetime IS NOT NULL,d.updatetime BETWEEN s.add_time AND 1473782399,1 = 1) and s.acttype = 1 GROUP BY s.uid limit $start,$offset");
        
        foreach ($joinInfo as &$v) {
            $v['addtime'] = date('Y-m-d', $v['addtime']);
        }

        $this->view->assign('prizeInfo', $prizeInfo);  
        $this->view->assign('countList', $countList);  //剩余数量
        $this->view->assign('list', $setList);  //用户中奖情况
        $this->view->assign('joinInfo', $joinInfo);  //用户参与情况
        $this->view->display('runningSports');
    }

    /**
     * 九月跑步运动会--指定用户获奖
     */
    public function dodistributionPrize()
    {
        $uid = common::request('uid', 'P');
        $prize = common::request('prize', 'P');
        if(empty($uid) || empty($prize))
        {
            exit("参数不完整！");
        }
        //判断用户是否存在
        $userInfo = $this->load('user')->getUserInfo($uid);
        if(empty($userInfo))
        {
            exit("该用户不存在!");
        }
        //判断用户是否参与了活动
        $isJoin = $this->db->getOne("select count(1) from r_sports_september where acttype = 1 and uid = {$uid}");
        if(empty($isJoin))
        {
            exit("该用户并未参与该活动！");
        }
        $this->db->update("update r_sports_september set specify_prize = {$prize} where acttype = 1 and uid = {$uid}");
        $this->dorunningSep();
    }

    /**
     * 中秋节吃货大作战管理后台
     */
    public function domidFoodie()
    {
        $p = common::request('p', 'G', 1);   //页码
        
        //中奖情况
        $setList = $this->db->getall("select * from r_winning_info where acttype = 2");
        //奖品字典
        $prizeInfo = array(
            '7' => '稻香村月饼礼盒',
            '8' => '哈根达斯200元现金卡',
            '9' => '哈根达斯100元现金卡',
            '10' => '10元话费'
        );
        foreach ($setList as &$v) {
            $v['prizeName'] = $prizeInfo[$v['prize']];
        }

        $countList = $this->db->getAll("select * from r_running_prize_sep where acttype = 2");
        foreach ($countList as &$v) {
            $v['prizeName'] = $prizeInfo[$v['prize']];
        }
        

        //参与情况  
        $joinCount = "select count(1) from r_sports_september where acttype = 2";

        $offset = 20;
        $num = $this->db->getOne($joinCount);

        //分页
        require FILE . 'lib/page.class.php';
        $page = new Page($num, $offset);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);

        $start = ($p - 1) * $offset;

        $joinInfo = $this->db->getAll("select s.uid,u.addtime,SUM(d.mileage) as mileage,COUNT(did) as count,s.draw_count from r_sports_september s LEFT JOIN r_user u ON s.uid = u.uid LEFT JOIN r_data d ON s.uid = d.uid WHERE IF(d.updatetime IS NOT NULL,d.updatetime BETWEEN s.add_time AND 1474127999,1 = 1) and s.acttype = 2 GROUP BY s.uid limit $start,$offset");
        
        foreach ($joinInfo as &$v) {
            $v['addtime'] = date('Y-m-d', $v['addtime']);
        }

        $this->view->assign('prizeInfo', $prizeInfo);  
        $this->view->assign('countList', $countList);  //剩余数量
        $this->view->assign('list', $setList);  //用户中奖情况
        $this->view->assign('joinInfo', $joinInfo);  //用户参与情况
        $this->view->display('midAutumn');
    }

    /**
     * 中秋节吃货大作战--指定用户获奖
     */
    public function dofoodiePrize()
    {
        $uid = common::request('uid', 'P');
        $prize = common::request('prize', 'P');
        if(empty($uid) || empty($prize))
        {
            exit("参数不完整！");
        }
        //判断用户是否存在
        $userInfo = $this->load('user')->getUserInfo($uid);
        if(empty($userInfo))
        {
            exit("该用户不存在!");
        }
        //判断用户是否参与了活动
        $isJoin = $this->db->getOne("select count(1) from r_sports_september where acttype = 2 and uid = {$uid}");
        if(empty($isJoin))
        {
            exit("该用户并未参与该活动！");
        }
        $this->db->update("update r_sports_september set specify_prize = {$prize} where acttype = 2 and uid = {$uid}");
        $this->domidFoodie();
    }

    /**
     * 虎扑跑步装备节管理后台
     */
    public function doEquipmentJoin()
    {
        $this->redisCache = $this->in_redis('cacheRedis');
        $p = common::request('p', 'G', 1);   //页码
        $uid = common::request('uid', 'P');   

        $joinCount = "select count(1) from r_sports_september where acttype = 3";
        !empty($uid) && $joinCount .= " and uid = {$uid}";

        $search = compact('uid');
        $offset = 20;
        $num = $this->db->getOne($joinCount);

        $parameter = "&uid=".$uid;
        //分页
        require FILE . 'lib/page.class.php';
        $page = new Page($num, $offset, $parameter);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);

        $start = ($p - 1) * $offset;

        $joinSql = "select s.uid,u.nickname,u.addtime,s.add_time,s.share_count,w.prize from r_sports_september s LEFT JOIN r_user u ON s.uid = u.uid LEFT JOIN r_winning_info w ON s.uid = w.uid AND w.acttype = 3 WHERE s.acttype = 3";
        !empty($uid) && $joinSql .= " and s.uid = {$uid}";
        $joinSql .= " GROUP BY s.uid order by s.add_time desc limit $start,$offset";

        $joinInfo = $this->db->getAll($joinSql);
        
        //抽字拼音字典
        $wordsPinyin = array('hu' => '虎', 'pu' => '扑', 'pao' => '跑', 'bu' => '步', 'zhuang' => '装', 'bei' => '备', 'jie' => '节');
        foreach ($joinInfo as &$v) {
            $v['addtime'] = date('Y-m-d', $v['addtime']);     //注册时间
            $v['add_time'] = date('Y-m-d', $v['add_time']);   //参与时间
            //集字情况
            $hasReceived = $this->redisCache->hgetall(REDIS_PREFIX . 'getPrizes_' . $v['uid']);
            $getWords = array();
            $hasWords = '';
            if(!empty($hasReceived)){
                $hasReceived = array_unique(array_values($hasReceived));
                foreach ($hasReceived as $key => $val) {
                    @$getWords[$key] = $wordsPinyin[$val];
                }
                $hasWords = implode(',', $getWords);
            }
            
            $v['hasWords'] = $hasWords;
            //是否中奖
            $v['isWinning'] = '否';
            
            $v['prize'] == 12 && $v['isWinning'] = '跑鞋';
            $v['prize'] == 13 && $v['isWinning'] = '优惠券';
        }

        //抽字字典
        $prizeWords = array('11' => '虎', '12' => '扑', '13' => '跑', '14' => '步', '15' => '装', '16' => '备', '17' => '节');
        
        $this->view->assign('search', $search);  //搜索条件
        $this->view->assign('prizeWords', $prizeWords);  //用户参与情况
        $this->view->assign('list', $joinInfo);  //用户参与情况
        $this->view->display('equipmentJoin');
    }

    /**
     * 虎扑跑步装备节--指定用户获奖
     */
    public function doEquipmentPrize()
    {
        $uid = common::request('uid', 'P');
        $prize = common::request('prize', 'P');
        if(empty($uid) || empty($prize))
        {
            exit("参数不完整！");
        }
        //判断用户是否存在
        $userInfo = $this->load('user')->getUserInfo($uid);
        if(empty($userInfo))
        {
            exit("该用户不存在!");
        }
        //判断用户是否参与了活动
        $isJoin = $this->db->getOne("select count(1) from r_sports_september where acttype = 3 and uid = {$uid}");
        if(empty($isJoin))
        {
            exit("该用户并未参与该活动！");
        }
        $this->db->update("update r_sports_september set specify_prize = {$prize} where acttype = 3 and uid = {$uid}");
        common::go("http://".$this->config['host'].'/admin/EquipmentJoin');
    }
    
    /*
     * 订单列表
     */
    public function doorderList(){
        $s = common::request('s','R','');
        $p = common::request('p','R',1);
        $query = ' where 1';
        $search = array(
            'nickname' => '',
            'order_id' => '',
            'phone' => '',
            'uid' => '',
            'status' => '',
            'shipping_num' => '',
            'startDate' => '',
            'endDate' => '',
            'act_type' => '-1',
            'act_id' => '',
        );
        $parameter = '';
        if($s == 'search'){
            $nickname = common::request('nickname','R','');
            $order_id = common::request('order_id','R','');
            $phone = common::request('phone','R','');
            $uid = common::request('uid','R','');
            $status = common::request('status','R','');
            $shipping_num = common::request('shipping_num','R','');
            $startDate = common::request('startDate','R','');
            $endDate = common::request('endDate','R','');
            $act_type = common::request('act_type','R','0');
            $act_id = common::request('act_id','R',0);
            
            if($nickname){
                $uid = $this->db->getOne("select uid from r_user where nickname='$nickname'");
            }
            $order_id && $query .= " and o.order_id = '{$order_id}'";
            $phone && $query .= " and o.phone ='{$phone}'";
            $uid && $query .= " and o.uid=$uid";
            $status && $query .= " and o.status='$status'";
            $shipping_num && $query .= " and a.shipping_num='$shipping_num'";
            if($act_type != '-1'){
                $query .= " and o.act_type='$act_type'";
                $act_id && $query .= " and o.act_id='$act_id'";
            }
            if($startDate){
                $stime = strtotime($startDate);
                $query .= " and o.addtime >= '$stime'";
            }
            if($endDate){
                $etime = strtotime($endDate);
                $query .= " and o.addtime <= '$etime'";
            }
            
            $search = compact('nickname','order_id','phone','uid','status','shipping_num','startDate','endDate','act_type','act_id');
            $parameter = $search;
            $parameter['s'] = 'search';
            $parameter = '&'.urldecode(http_build_query($parameter, NULL, '&'));
        }
        
        //分页
        require FILE . 'lib/page.class.php';
        $listNum = 100;
        $start = ($p - 1) * $listNum;
        
        $this->in_erpDb();
        $num = $this->erpDb->getOne('select count(*) from r_order as o left join r_order_action as a on a.order_id = o.order_id'.$query);
        $page = new Page($num, $listNum, $parameter);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);
        
        $orderList = $this->erpDb->getAll('select o.*,a.id as action_id,a.shipping_status,a.shipping_num from r_order as o left join r_order_action as a on a.order_id = o.order_id'.$query." order by id desc limit $start,$listNum");
        $client_mod = $this->load('client');
        foreach($orderList as &$row){
            $row['user'] = $client_mod->getUserInfo($row['uid']);
            $dabiao = 0;
            if($row['match_id']){
                $dabiao = $this->db->getOne("select dabiao from r_match_add where `type`='user' and uid={$row['uid']} and match_id={$row['match_id']} limit 1");
            }
            $row['dabiao'] = $dabiao;
        }
        
        $this->view->assign('search', $search);
        $this->view->assign('orderList', $orderList);
        $this->view->assign('orderStatus',common::$orderStatus);
        $this->view->assign('actType',common::$actType);
        $this->view->assign('payStatus', common::$payStatus);
        $this->view->display('orderList');
    }
    
    /*
     * 订单详情
     */
    public function doorderInfo(){
        $id = common::request('id','G');
        $this->in_erpDb();
        $orderInfo = $this->erpDb->getRow('select o.*,a.id as action_id,a.shipping_status,a.shipping_num from r_order as o left join r_order_action as a on a.order_id = o.order_id where o.id='.$id);
        $orderInfo['user'] = $this->load('client')->getUserInfo($orderInfo['uid']);
        $goodsList = [];
        $goods_mod = $this->load('goods');
        $orderInfo['goods'] = json_decode($orderInfo['goods'],true);
        foreach($orderInfo['goods'] as $_goods){
            if ($orderInfo['act_type'] == 6) {
                $liveInfo = $this->load('live/live')->getLiveInfo($_goods['id'], 'title, image_url, price');
                if(empty($liveInfo)){
                    continue;
                }
                $goodsInfo = array(
                    'product'=>[
                        'id'=>0,
                        'code'=>'',
                        'title'=>$liveInfo['title'],
                        'is_virtual'=>1,
                        'imageCnt'=>1,
                        'imageList'=>[$liveInfo['image_url']]
                    ],
                    'goodsInfo'=>[
                        'attrPathName'=>'报名费',
                        'stockNum'=>0,
                        'saleNum'=>0,
                        'saleprice'=>$liveInfo['price'],
                        'erpRealStockNum'=>0,
                        'erpGoodId'=>0,
                    ]
                );
            }else  if ($orderInfo['act_type'] == 7) {
                $goldConfiguration = common::$goldConfiguration;
                $configGood = isset($goldConfiguration[$_goods['id']]) ? $goldConfiguration[$_goods['id']] : [];
                $goodsInfo = array(
                    'product'=>[
                        'id'=>0,
                        'code'=>'',
                        'title'=>'充值元宝',
                        'is_virtual'=>1,
                        'imageCnt'=>1,
                        'imageList'=>''
                    ],
                    'goodsInfo'=>[
                        'attrPathName'=>'充值元宝',
                        'stockNum'=>0,
                        'saleNum'=>0,
                        'saleprice'=>$configGood && isset($configGood['costPrice']) ? $configGood['costPrice'] : 0,
                        'erpRealStockNum'=>0,
                        'erpGoodId'=>0,
                    ]
                );
            } else {
                $goodsInfo = $goods_mod->getRaceGoodsInfo($_goods['id']);
            }
            $goodsInfo['goodsInfo'] = array_merge($_goods,$goodsInfo['goodsInfo']);
            $goodsList[] = $goodsInfo;
        }
        $orderInfo['goodsList'] = $goodsList;
        
        $logisticsTepList = $this->load('adminErp')->getLogisticsTepList(['start'=>0,'limit'=>20]);
        array_unshift($logisticsTepList,['id'=>0,'title'=>'']);

        $haitaoInfo = array();
        if($orderInfo['act_type']==8){
            $sql = "select * from r_order_haitao where order_id='".$orderInfo['order_id']."'";
            $haitaoInfo = $this->erpDb->getRow($sql);
        }
        
        $this->view->assign('orderInfo', $orderInfo);
        $this->view->assign('haitaoInfo', $haitaoInfo);
        $this->view->assign('orderStatus',common::$orderStatus);
        $this->view->assign('payStatus', common::$payStatus);
        $this->view->assign('logisticsTepList',$logisticsTepList);
        $this->view->display('orderInfo');
    }
    
    /*
     * 订单操作
     */
    public function doorderAction(){
        $id = common::request('id','P');
        $status = common::request('status','P','');
        $name = common::request('name','P','');
        $province = common::request('privince','P','');
        $city = common::request('city','P','');
        $district = common::request('district','P','');
        $address = common::request('address','P','');
        $phone = common::request('phone','P','');
        $order_id = common::request('order_id','P','');
        
        $action_id = common::request('action_id','P','');
        $shipping_id = common::request('shipping_id','P','');
        $shipping_num = common::request('shipping_num','P','');
        
        if(empty($id) || empty($order_id)){
            die('<a href="?c=admin&a=orderList" >id错误，点击返回</a>');
        }
        $this->in_erpDb();
        $row = $this->erpDb->getRow("select id,goods from r_order where status=1 AND pay_status='10' AND id=$id");
        if(!empty($row)&&$status==3){
            $goods_mod = $this->load('goods');
            $goods = json_decode($row['goods']);
            if($goods){
                foreach($goods as $g){
                    $goods_mod->rollbackFlashGoodsSaleNum($g->id,$g->num);
                }
            }
        }

        $res = $this->erpDb->updateRowTable('r_order',compact('id','status','name','province','city','district','address','phone','shipping_id'));
        
        $actionInfo = compact('order_id','shipping_id','shipping_num');
        $actionInfo['id'] = $action_id;
        $actionInfo['uid'] = $this->realUser['uid'];
        $this->load('order')->addOrderAction($actionInfo);
        
        exit("<a href='?c=admin&a=orderInfo&id={$id}'>完成，点击返回</a>");
    }
    
    /*
     * 商品列表
     */
    public function dogoodsList(){
        $match_id = common::request('match_id','G');
        $action = common::request('action','G','');
        $product_id = common::request('product_id','G','');
        if(empty($match_id)){
            die('参数错误');
        }
        
        if($action == 'del' && $product_id){
            $this->load('goods')->saveRaceStatus($match_id,$product_id);
            common::go('?c=admin&a=goodsList&match_id='.$match_id);
        }
        
        $goodsList = $this->load('goods')->getRaceGoodsList($match_id);
        $this->view->assign('goodsList',$goodsList);
        $this->view->assign('match_id',$match_id);
        $this->view->display('goodsList');
    }
    
    /*
     * 商品详情
     * @product_code like P43ba28a9
     */
    public function dogoodsInfo(){
        $match_id = common::request('match_id','R');
        $product_code = common::request('product_code','R');
        $product_id = common::request('product_id','P');
        $nums = common::request('nums','P');
        $prices = common::request('prices','P');
        $goods_ids = common::request('goods_ids','P');
        $sort = common::request('sort','P',0);
        
        if(empty($match_id) || empty($product_code)){
            die('参数错误');
        }
        
        if($goods_ids && $nums && $prices){
            $goods_mod = $this->load('goods');
            foreach($goods_ids as $k=>$goods_id){
                $goods_mod->addRaceGoods($match_id,$product_id,$goods_id,$nums[$k],$prices[$k],$sort);
            }
            common::go('/index.php?c=admin&a=goodsList&match_id='.$match_id);
        }
        
        $product = $this->load('adminErp')->getGoodsListByProductCode($product_code);
        if(empty($product)){
            common::tips('货号有误','?c=admin&a=goodsList&match_id='.$match_id);
        }
        $this->view->assign('product',$product);
        $this->view->display('goodsInfo');
    }
    
    /*
     * 获得经纬度
     */
    public function dogetCoordinate(){
        $did = common::request('did','G');
        if(empty($did)){
            die('did wrong');
        }
        
        $coordinate = $this->db->getOne('select coordinate from r_data_ext where did='.$did);
        echo gzuncompress(base64_decode($coordinate));
    }

    /*
     * 个人中心导航
     */
    public function douserChannel(){
        $titles = common::request('titles','P');
        $schemes = common::request('schemes','P');
        $sorts = common::request('sorts','P');
        
        $userChannel = $this->load('client')->getUserChannel();
        /*if(empty($userChannel)){
            $userChannel = array(
                array(
                    'title' => '活动',
                    'image' => 'http://' . $this->config['host'] . '/static/images/geren_huodong.png',
                    'scheme' => 'http://irun.hupu.com/show/activityList',
                ),
                array(
                    'title' => '打卡目标',
                    'image' => 'http://' . $this->config['host'] . '/static/images/geren_daka.png',
                    'scheme' => 'joggers://user/target',
                ),
                array(
                    'title' => '装备', 
                    'image' => 'http://' . $this->config['host'] . '/static/images/geren_zhuangbei.png',
                    'scheme' => 'joggers://bbs/gear',
                ),
            );
            $this->redis->SET(REDIS_PREFIX.'userChannel',json_encode($userChannel));
        }*/
        
        if($sorts){
            $new_userChannel = array();
            foreach($sorts as $key=>$sort){
                if($sort===''){
                    continue;
                }
                if(isset($userChannel[$key])){
                    $image = $this->load('qiniu')->uploadQiNiuImg('image_'.$key, md5(time().'userMenu_'.$key));
                    $new_userChannel[$sort]['image'] = $image ? $image : $userChannel[$key]['image'];
                }else{
                    $image = $this->load('qiniu')->uploadQiNiuImg('image_x', md5(time().'userMenu_'.$key));
                    $new_userChannel[$sort]['image'] = $image ? $image : '';
                }
                $new_userChannel[$sort]['title'] = $titles[$key];
                $new_userChannel[$sort]['scheme'] = $schemes[$key];
            }
            !empty($new_userChannel) && ksort($new_userChannel);
            $userChannel = $new_userChannel;
            $this->redis->SET(REDIS_PREFIX.'userChannel',json_encode($new_userChannel));
        }
        
        $this->view->assign('userChannel',$userChannel);
        $this->view->display('userChannel');
    }

    /**
     * 热修复管理
     */
    public function dogetHotRepairList() {
        $listNum = 10;
        $p = common::request('p', 'G', 1);
        $start = ($p - 1) * $listNum;
        $info = $this->db->getAll("select * from r_hot_repair order by create_time desc limit $start,$listNum");
        $total = $this->db->getOne("select count(1) as cnt from r_hot_repair");
        $this->view->assign('info', $info);
        require FILE . 'lib/page.class.php';
        $page = new Page($total, $listNum);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);
        $this->view->display('system/hotRepairList');
    }

    /**
     * 热修复状态更新
     */
    public function dosetHotRepairStatus() {
        $repairId = common::request('repairId','R',0);
        $status = common::request('status','R',0);
        if (!$repairId) {
            echo  json_encode(array('status'=>'fail','error_msg'=>'参数丢失'));exit;
        }
        if (!$info = $this->db->getRow("select * from r_hot_repair where id=$repairId")) {
            echo  json_encode(array('status'=>'fail','error_msg'=>'修复包不存在'));exit;
        }
        if ($status == 1) {
            $this->db->update("update  r_hot_repair set status=1 where id=$repairId");
        } else {
            $this->db->update("update  r_hot_repair set status=0 where id=$repairId");
        }
        echo  json_encode(array('status'=>'ok','error_msg'=>'成功','url'=>'?c=admin&a=getHotRepairList'));exit;
    }

    /**
     * 创建/编辑补丁
     */
    public function doaddHotRepair() {
        $repairId = common::request('repairId', 'R', 0);
        $info = [];
        if ($repairId) {
            $info = $this->db->getRow("select * from r_hot_repair where id=$repairId");
            if (!$info) {
                common::tips('热修复补丁不存在');exit;
            }
            //查询热修复补丁
            $patchList = $this->db->getAll("select * from r_hot_repair_file where repair_id=$repairId and status=0");
            $info['patchList'] = [];
            if ($patchList) {
                foreach ($patchList as $key=>$val) {
                    $plist[] = array('id'=>$val['id'],'file_name'=>$val['file_name'],'file_hash'=>$val['file_hash']);
                }
                $info['patchList'] = $plist;
            }
        }
//        var_dump($info);
        $this->view->assign('repairId',$repairId);
        $this->view->assign('info',$info);
        $this->view->display('system/addHotRepair');
    }

    /**
     * 上传热修复补丁
     */
    public function doajaxUploadRepair() {
//        var_dump($_FILES);exit;
        if (!$_FILES || ($_FILES['imgFile']['size'] == 0)) {
            echo json_encode(array('status'=>'fail','error_msg'=>'请选择上传文件!'));
            exit;
        }
        $imageName ='patch_'.md5(microtime(TRUE).$_FILES['imgFile']['name']);
        $image_url = $this->load('qiniu')->uploadQiNiuHotRepart('imgFile',$imageName);
        if (!$image_url) {
            echo json_encode(array('status'=>'fail','error_msg'=>'上传失败!'));
            exit;
        }
        $inputnameArr = explode('.', $_FILES['imgFile']['name']);
        $imgExtention = strtolower(end($inputnameArr));
        $fileName = empty($imageName)? $_FILES['imgFile']['name'] : $imageName.'.'.$imgExtention;
        echo json_encode(array('status'=>'ok','error_msg'=>'上传成功','image'=>$image_url,'file_hash'=>hash_file('MD5',$image_url),'file_name'=>$fileName));
    }

    /**
     * ajax 创建/编辑补丁
     */
    public function doajaxAddHotRepair()
    {
        $repairId = common::request('repairId', 'R', 0);
        $clientId = (int)common::request('clientId', 'R', 1);
        //$patchVersion = common::request('patchVersion', 'R', 0);
        $appVersion = common::request('appVersion', 'R', '');
        $fileName = common::request('fileName', 'R', []);
        $fileUrl = common::request('image', 'R', []);

        if (!$clientId || !in_array($clientId, array(1, 2))) {
            echo json_encode(array('status' => 'fail', 'error_msg' => '参数错误!'));
            exit;
        }
//        if (!preg_match('/^[0-9]+$/',$patchVersion,$match)) {
//            echo json_encode(array('status'=>'fail','error_msg'=>'请填写数字版本号!'));
//        }
        if (!$fileName || !$fileUrl) {
            echo json_encode(array('status' => 'fail', 'error_msg' => '文件清单不存在或清单参数错误!'));
            exit;
        }
        $fields = [];
        $fields['client_type'] = $clientId;
        $fields['app_version'] = $appVersion;
        if ($repairId) {
            $setStr = common::arrayToString($fields);
            $r = $this->db->update("update r_hot_repair set $setStr where id=$repairId");
            if ($r) {
                //查询文件清单
                $plist = $this->db->getAll("select * from r_hot_repair_file where repair_id=$repairId and status=0");
                $arrOldFile = [];
                if ($plist) {
                    foreach ($plist as $key => $val) {
                        $arrOldFile[$val['id']] = $val['file_name'];
                    }
                }

                $arrAdd = array_diff((array)$fileName, (array)$arrOldFile);
                $arrDel = array_diff((array)$arrOldFile, (array)$fileName);
                if ($arrAdd) {
                    foreach ($arrAdd as $k => $v) {
                        $data = [];
                        $data['repair_id'] = $repairId;
                        $data['file_name'] = $v;
                        $data['file_hash'] = $fileUrl[$k] ? hash_file('MD5', $fileUrl[$k]) : '';
                        $data['file_url'] = $fileUrl[$k] ? $fileUrl[$k] : '';
                        $data['create_time'] = time();
                        $this->db->insertRow('r_hot_repair_file', $data, 0);
                    }
                }
                if ($arrDel) {
                    foreach ($arrDel as $kd => $vd) {
                        $this->db->update("update r_hot_repair_file set status=-5 where id=$kd");
                    }
                }
                echo json_encode(array('status' => 'ok', 'error_msg' => '操作成功', 'url' => '?c=admin&a=getHotRepairList'));
                exit;
            }
            echo json_encode(array('status' => 'fail', 'error_msg' => '操作失败'));
            exit;
        }

        //查询补丁号
        $patchVersion = $this->db->getOne("select patch_version from r_hot_repair ORDER BY patch_version DESC limit 1");
        $patchVersion = $patchVersion ? $patchVersion + 1 : 1000;


        $fields['patch_version'] = $patchVersion;
        $fields['create_time'] = time();

        $r = $this->db->insertRow('r_hot_repair', $fields, 0);
        if ($r) {
            foreach ($fileName as $k => $v) {
                $data = [];
                $data['repair_id'] = $r;
                $data['file_name'] = $v;
                $data['file_hash'] = $fileUrl[$k] ? hash_file('MD5', $fileUrl[$k]) : '';
                $data['file_url'] = $fileUrl[$k] ? $fileUrl[$k] : '';
                $data['create_time'] = time();
                $this->db->insertRow('r_hot_repair_file', $data, 0);
            }
            echo json_encode(array('status' => 'ok', 'error_msg' => '操作成功', 'url' => '?c=admin&a=getHotRepairList'));
            exit;
        }
        echo json_encode(array('status' => 'fail', 'error_msg' => '操作失败'));
        exit;
    }

    public function  dogetRepairFile() {
        $repairId = common::request('repairId', 'R', 0);
        if (!$repairId) {
            echo json_encode(array('status' => 'fail', 'error_msg' => '参数丢失'));exit;
        }
        $arrFile = $this->db->getAll("select file_url from r_hot_repair_file where repair_id = $repairId and status=0");
        $list = [];
        if (!$arrFile) {
            echo json_encode(array('status' => 'fail', 'error_msg' => '没找到下载的资源'));exit;
        }
        foreach($arrFile as $val) {
            $list[] = $val['file_url'];
        }

        echo json_encode(array('status' => 'ok', 'list' => $list));exit;
    }

    /**
     * 下载热修复文件
     */
    public function dodownLoadHotRepairFile() {
//        $repairId = common::request('repairId', 'R', 0);
//        if (!$repairId) {
//            echo json_encode(array('status' => 'fail', 'error_msg' => '参数丢失'));exit;
//        }
//        $arrFile = $this->db->getAll("select file_name,file_url from r_hot_repair_file where repair_id = $repairId and status=0");
//        if (!$arrFile) {
//            echo json_encode(array('status' => 'fail', 'error_msg' => '参数有误'));exit;
//        }
//        $file_name = iconv("utf-8","gb2312",$arrFile['file_name']);
        $file_path = common::request('filepath', 'R', 0);
        header("Content-type:text/html;charset=utf-8");
        //$file_path = $arrFile['file_url'];
        Header("Content-type: application/octet-stream");
        Header("Accept-Ranges: bytes");
        Header("Content-Disposition: attachment; filename=".basename($file_path));
        readfile($file_path);
        exit;
    }
    
    /*
     * 合作第三方绑定用户列表
     */
    public function dopartneruser(){
        $p = common::request('p', 'R', 1);
        $partner_name = common::request('partner_name','P','alibaba_sports');
        $num = $this->db->getOne("select count(*) from r_partner_user where partner_name='{$partner_name}'");
        
        $search = compact('partner_name');
        
        //分页
        require FILE . 'lib/page.class.php';
        $listNum = 200;
        $start = ($p - 1) * $listNum;
        $parameter = compact('p','partner_name');
        $parameter = '&'.urldecode(http_build_query($parameter, NULL, '&'));
        $page = new Page($num, $listNum, $parameter);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);
        
        $userList = $this->db->getAll("select * from r_partner_user where partner_name='{$partner_name}' order by id desc limit $start,$listNum");
        $client_mod = $this->load('client');
        foreach($userList as &$pu){
            $userInfo = $client_mod->getUserInfo($pu['uid']);
            $pu['nickname'] = $userInfo['nickname'];
        }
        $this->view->assign('search',$search);
        $this->view->assign('userList',$userList);
        $this->view->display('partnerUserList');
    }
}
 